/*
 * FormBuilder Methods
 */

function NotifyMe(element_affected, message) {
    if (typeof message == "undefined") {
        //catch errr
        message = '';
    }
    var this_element = $(element_affected);
    var this_id_object_data = $(element_affected).attr("data-object-id");
    var this_element_name = $(element_affected).attr("name");
    var element_container = this_element.parent();
    var element_ptop = this_element.position().top;
    var element_pleft = this_element.position().left;
    var element_pright = this_element.position().left + this_element.outerWidth();
    var element_pbottom = this_element.position().top + this_element.outerHeight();
    var noti_ele = $(
            '<div class="NM-notification" nm-unique-attr="' + this_element_name + this_id_object_data + '" style="z-index:500;padding:5px;"><div class="arrow-left"></div>' + message + '</div>'
            )

    this_element.addClass("NM-redborder");
    if (element_container.children(".NM-notification[nm-unique-attr='" + this_element_name + this_id_object_data + "']").length == 0) {
        element_container.append(noti_ele);
        $(noti_ele).css({
            "top": (element_ptop) + "px",
            "left": (element_pright + 5) + "px",
            "padding": "8px",
            "color": "#ffffff",
            "text-align": "center",
            "text-decoration": "none",
            "position": "absolute",
            "-webkit-border-radius": "4px",
            "-moz-border-radius": "4px",
            "border-radius": "4px",
            "background-color": "#000000",
            "z-index": (500)
        });
        $(noti_ele).children(".arrow-left").eq(0).css({
            "width": "0px",
            "height": "0px",
            "border-top": "10px solid transparent",
            "border-right": "10px solid #000000",
            "position": "absolute",
            "top": "5px",
            "left": "0px",
            "margin-left": "-5px"
        });
        var mouse_entered = "not yet";
        var event_name_mouseenter = "mouseenter.EventNotifyMe" + this_id_object_data;
        // var event_name_focusin = "focusin.EventNotifyMe";

        noti_ele.on(event_name_mouseenter, function() {
            if (mouse_entered == "not yet") {
                noti_ele.fadeOut(2500, function() {
                    $(this).remove();
                });
                mouse_entered = "yes";
                $(this).off(event_name_mouseenter);
            }
        });
        // this_element.on(event_name_focusin, function() {
        //         $(this).removeClass("frequired-red");
        //         if (noti_ele.length >= 1) {
        //             noti_ele.fadeOut(1000, function() {
        //                 $(this).remove();
        //             });
        //         }
        // });
        this_element.on(event_name_mouseenter, function() {
            $(this).removeClass("NM-redborder");
            if (noti_ele.length >= 1) {
                noti_ele.fadeOut(2500, function() {
                    $(this).remove();
                });
            }
            $(this).off(event_name_mouseenter);
        });
    } else if (element_container.children(".NM-notification[nm-unique-attr='" + this_element_name + this_id_object_data + "']").length == 1) {
        noti_ele = element_container.children(".NM-notification[nm-unique-attr='" + this_element_name + this_id_object_data + "']");
        if (noti_ele.text().indexOf(message) >= 0) {

        } else {
            noti_ele.append("<br/>" + message);
        }
    }
}
var count = "1";
var count_btn = "1";
form_settings_get_objects = {
    form_property_pane_fluid: function() {
        $(window).resize(function() {
            var window_outer_height = $(this).outerHeight();
            var form_property_bottom = ($(".form_properties").offset().top + $(".form_properties").outerHeight());
            if (window_outer_height < form_property_bottom) {

            }
            // alert($(this).outerHeight()+" == "+ ($(".form_properties").offset().top+$(".form_properties").outerHeight()))
        })
    },
    get_objects: function(elements) {
        // Upload Image to the form 
        $("#formImage").change(function() {
            $("#getformImage").ajaxForm(function(data) {
                if (data == "Invalid File Format") {
                    showNotification({
                        message: data,
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                    $(".filename").html("No file selected");
                } else if (data == "File too large. File must be less than 4 megabytes") {
                    showNotification({
                        message: data,
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                    $(".filename").html("No file selected");
                } else {
                    var json = $.parseJSON(data);
                    if (json[0].successful == "Your new photos was successfully uploaded.") {
                        imageForm = $(getimageForm(count, "imageForm", json[0].img));
                        $("." + "workspace").append(imageForm);
                        $(imageForm).css({
                            "top": (drop_top) + "px",
                            "left": (drop_left) + "px"
                        });
                        dragObects($(imageForm), "." + "workspace", $("." + "workspace").height, count);
                        count++;
                    }
                }
            }).submit();
        });
        
        
        
        

        $("body").on("click", elements, function() {
            var object_type = $(this).attr("data-object-type");
            var object_drop = $(this).attr("data-drop");
            var container_height = $("." + object_drop).height();
            //Call a function of object type to add an object to the workspace.
            // if($('.setObject[unpositioned="true"]').length <= 10){

            // }else{
            // 	alert("please position first all the unpositioned objects");
            // }
            objType(object_type, object_drop, count, container_height);
            count++;
            bind_onBeforeOnload(1);
        });
    },
    getFieldNameErrors: function() {
        var collect_names = [];//COMPARING IF THERE IS THE SAME NAME
        var errors = 0;
        $(".workspace.formbuilder_ws").find(".setObject").each(function() {
            if (
                    $(this).attr("data-type") != "table" &&
                    $(this).attr("data-type") != "tab-panel" &&
                    $(this).attr("data-type") != "labelOnly" &&
                    $(this).attr("data-type") != "createLine" &&
                    $(this).attr("data-type") != "embeded-view" &&
                    $(this).attr("data-type") != "imageOnly"
                    ) {
                var dis_id = $(this).attr("data-object-id");
                var dis_fieldname = $(this).find(".getFields_" + dis_id).eq(0).attr("name");
                var dis_field_data_type = $(this).find(".getFields_" + dis_id).eq(0).attr("type");
                // alert(typeof dis_field_data_type == "undefined")
                if (collect_names.length >= 1) {
                    // console.log(collect_names[collect_names.length-1].fieldname)
                    // console.log(collect_names.indexOf("fn90"))
                    var founds = 0;
                    for (var ctr = 0; ctr < (collect_names.length); ctr++) {
                        // console.log(collect_names[ctr].fieldname+" == "+dis_fieldname)
                        if (collect_names[ctr].fieldname == dis_fieldname) {
                            // collect_names[ctr].DOMJQuery.css({
                            //     "border":"2px solid red"
                            // });
                            // $(this).css({
                            //     "border":"2px solid red"
                            // });
                            NotifyMe($(this), "This name '" + dis_fieldname + "' has an identical name");
                            NotifyMe(collect_names[ctr].DOMJQuery, "This name '" + collect_names[ctr].fieldname + "' has an identical name");
                            founds++;
                            errors++;
                        }
                    }
                    if (founds == 0) {
                        collect_names.push({
                            "fieldname": dis_fieldname,
                            "data_object_id": dis_id,
                            "DOMJQuery": $(this)
                        })
                    }
                } else {
                    collect_names.push({
                        "fieldname": dis_fieldname,
                        "data_object_id": dis_id,
                        "DOMJQuery": $(this)
                    });
                }
                // console.log("ETO")
                // console.log(dis_fieldname.match(/^[A-Za-z_][A-Za-z0-9_]*$/g))
                var reggy_match = /^[A-Za-z_][A-Za-z0-9_]*$/g; //THIS IS FOR CHECKBOX
                if (typeof dis_field_data_type != "undefined") {
                    if (dis_field_data_type == "checkbox") {
                        reggy_match = /^[A-Za-z_][A-Za-z0-9_]*\[\]$/g;
                    }
                }
                var fieldname_keywords = [
                    "FormID", "WorkflowId", "ID",
                    "Requestor", "CurrentUser", "Status",
                    "Processor", "LastAction", "DateCreated",
                    "DateUpdated", "CreatedBy", "UpdatedBy",
                    "Unread", "Node_ID", "Workflow_ID",
                    "Mode", "TrackNo", "imported",
                    "computedFields", "fieldEnabled", "KeywordsField",
                    "Repeater_Data", "Department_Name", "From",
                    "To"
                ];
                // var fieldname_keywords = [];
                // $(".fieldname-keywords").each(function(){
                //     if($(this).attr("name")){
                //         if($(this).attr("name").length >= 1){
                //             fieldname_keywords.push($(this).attr("name"));
                //         }
                //     }
                // })
                //console.log("FIELDNAMES CHECK");
                //console.log(dis_fieldname)
                //console.log(dis_fieldname.match(reggy_match))
                if(dis_fieldname){
                    if (dis_fieldname.match(reggy_match) == null) {
                        NotifyMe($(this), "Invalid field name! -> '" + dis_fieldname + "'");
                        if (dis_fieldname.match(/^[^A-Za-z_]/g) != null) {
                            NotifyMe($(this), "Field name doesn't start with letters!");
                        }
                        if (dis_fieldname.match(/[^A-Za-z0-9_]+/g) != null) {
                            NotifyMe($(this), "Special characters are not allowed!");
                        }

                        errors++;
                    } else if (fieldname_keywords.indexOf(dis_fieldname) >= 0) {
                        NotifyMe($(this), "Require to change this name.");
                        errors++;
                    }
                }
                    if (dis_fieldname.match(reggy_match) == null) {
                        NotifyMe($(this), "Invalid field name! -> '" + dis_fieldname + "'");
                        if (dis_fieldname.match(/^[^A-Za-z_]/g) != null) {
                            NotifyMe($(this), "Field name doesn't start with letters!");
                        }
                        if (dis_fieldname.match(/[^A-Za-z0-9_]+/g) != null) {
                            NotifyMe($(this), "Special characters are not allowed!");
                        }

                        errors++;
                    } else if (fieldname_keywords.indexOf(dis_fieldname) >= 0) {
                        NotifyMe($(this), "Require to change this name.");
                        errors++;
                    }
            }
        });
        $(".formbuilder_page_btn.btn_content").find(".setObject").each(function() {
            var dis_id = $(this).attr("data-object-id");
            var dis_fieldname = $(this).find("#btnName_" + dis_id).eq(0).attr("name");
            if (collect_names.length >= 1) {
                // console.log(collect_names[collect_names.length-1].fieldname)
                // console.log(collect_names.indexOf("fn90"))
                var founds = 0;
                for (var ctr = 0; ctr < (collect_names.length); ctr++) {
                    // console.log(collect_names[ctr].fieldname+" == "+dis_fieldname)
                    if (collect_names[ctr].fieldname == dis_fieldname) {
                        // collect_names[ctr].DOMJQuery.css({
                        //     "border":"2px solid red"
                        // });
                        // $(this).css({
                        //     "border":"2px solid red"
                        // });
                        NotifyMe($(this), "This name '" + dis_fieldname + "' has an identical name");
                        NotifyMe(collect_names[ctr].DOMJQuery, "This name '" + collect_names[ctr].fieldname + "' has an identical name");
                        founds++;
                        errors++;
                    }
                }
                if (founds == 0) {
                    collect_names.push({
                        "fieldname": dis_fieldname,
                        "data_object_id": dis_id,
                        "DOMJQuery": $(this)
                    })
                }
            } else {
                collect_names.push({
                    "fieldname": dis_fieldname,
                    "data_object_id": dis_id,
                    "DOMJQuery": $(this)
                });
            }
            // console.log("ETO")
            // console.log(dis_fieldname.match(/^[A-Za-z_][A-Za-z0-9_]*$/g))
            var reggy_match = /^[A-Za-z_][A-Za-z0-9_]*$/g; //THIS IS FOR CHECKBOX
            if (typeof dis_field_data_type != "undefined") {
                if (dis_field_data_type == "checkbox") {
                    reggy_match = /^[A-Za-z_][A-Za-z0-9_]*\[\]$/g;
                }
            }
            if (dis_fieldname) {
                if (dis_fieldname.match(reggy_match) == null) {
                    NotifyMe($(this), "Invalid field name! -> '" + dis_fieldname + "'");
                    if (dis_fieldname.match(/^[^A-Za-z_]/g) != null) {
                        NotifyMe($(this), "Field name doesn't start with letters!");
                    }
                    if (dis_fieldname.match(/[^A-Za-z0-9_]+/g) != null) {
                        NotifyMe($(this), "Special characters are not allowed!");
                    }
                    errors++;
                }
            }
        });
        return errors;
    },
    // Set Size of Form
    form_size: function(elements) {
        $("body").on("change", elements, function() {
            var size = $(this).val();

            // Split Form Size Value
            var form_size = size.split("x");
            var form_size_width = form_size[0];
            var form_size_height = form_size[1];

            tppi_w = $('<div id="ppitestw" style="width:1in;visible:hidden;padding:0px"></div>');
            tppi_h = $('<div id="ppitesth" style="height:1in;visible:hidden;padding:0px"></div>');
            $("body").append(tppi_w);
            $("body").append(tppi_h);
            screenPIW = $("#ppitestw").width();
            screenPIH = $("#ppitesth").height();
            form_width = (form_size_width * screenPIW);
            form_height = (form_size_height * screenPIH);

            if (form_width <= checkFormMinWidth()) {
                form_width = checkFormMinWidth();
            }
            if (form_height <= checkFormMinHeight()) {
                form_height = checkFormMinHeight();
            }

            $(".workspace").css({
                "width": form_width + "px",
                "height": form_height + "px"
            });

            $(".form_size_width").val(form_width);
            $(".form_size_height").val(form_height);
            tppi_w.remove();
            tppi_h.remove();
        });
    },
    form_set_size: function(element) { //DITO NA AKO!!!
        numericFunction(element);

        $("body").on("keyup", element, function() {
            var form_size_width = $(".form_size_width").val();
            var form_size_height = $(".form_size_height").val();
            if (form_size_width >= 100 && form_size_height >= 100) {
                if (form_size_width <= checkFormMinWidth()) {
                    form_size_width = checkFormMinWidth();
                }
                if (form_size_height <= checkFormMinHeight()) {
                    form_size_height = checkFormMinHeight();
                }

                $(".workspace").css({
                    "width": form_size_width + "px",
                    "height": form_size_height + "px"
                });

                $(".form_size_width").val(form_size_width);
                $(".form_size_height").val(form_size_height);
            }

        });

    },
    clear_all: function(elements) {
        $("body").on("click", elements, function() {
            var conf = "Are you sure you want to clear all?";
            jConfirm(conf, 'Confirmation Dialog', '', '', '', function(r) {
                if (r == true) {
                    $(".setObject").each(function() {
                        $(this).remove();
                    });
                }
            });
        });
    },
    delete_objects: function(elements) {
        $("body").on("click", elements, function() {
            var body_data = $("body").data();
            var object_id = $(this).attr("data-object-id");
            // $(".object_properties").popover('hide');
            con = "Are you sure do you want to delete this object?";
            jConfirm(con, 'Confirmation Dialog', '', '', '', function(r) {
                if (r == true) {
                    $("#setObject_" + object_id).remove();

                    if (typeof body_data[object_id] != "undefined") {
                        delete body_data[object_id];
                        console.log("NAGDELETE")
                        console.log(body_data)
                    }
                    // Get Btn length
                    var btn_length = $(".setObject_btn").length;
                    // Show btn label on formbuilder

                    if (btn_length < 1) {
                        $(".ws_btn_label").show();
                    }
                    if ($(".setObject").length == 0) {
                        bind_onBeforeOnload(0);
                    } else {
                        bind_onBeforeOnload(1);
                    }
                }
            });
            $("body").data(body_data);
        });
    },
    save_form_workspace: function(elements) {
        self = this;
        $("body").on("click", elements, function() {
            var pathname = window.location.pathname;
            if (pathname != "/formbuilder") {
                return;
            }
            if (form_settings_get_objects.getFieldNameErrors() == 0) {
                var form_type = $(this).attr("data-form-type");
                // Settings
                var workspace_title = $(".workspace_title").val();
                var workspace_displayName = $(".workspace_displayName").val();
                var workspace_categoryname = $(".form_category option:selected").val();
                var workspace_prefix = $(".workspace_prefix").val();
                var workspace_type = $(".workspace_type option:selected").val();
                var workspace_width = $(".form_size_width").val();
                var workspace_height = $(".form_size_height").val();

                switch (form_type) {

                    case "formbuilder":

                        if ($(".form-builder-ruler").length >= 1) {
                            $(".form-builder-ruler").remove()
                        }

                        // Get Object Length

                        var object_length = $(".setObject").length;
                        // Get Button Length
                        var btn_length = $(".setObject_btn").length;


                        // Condition if workspace is null
                        if (object_length < 1) {
                            // Notification
                            jAlert("Workspace is empty.", "", "", "", "", function() {
                            });
                        } else if (btn_length < 1) {
                            jAlert("Add atleast one button.", "", "", "", "", function() {
                            });
                        } else if (workspace_title == "") {
                            showNotification({
                                message: "Title is empty.",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        } else if (workspace_displayName == "") {
                            showNotification({
                                message: "Display Name is empty.",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        } else if (workspace_prefix == "") {
                            showNotification({
                                message: "Prefix is empty.",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        } else if (workspace_type == "0") {
                            showNotification({
                                message: "Please select a type.",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        } else {
                            $(".saveFormLoad").show();
                            var form_Fields_Arr = new Array();
                            // Get Fields Name
                            //    var form_fields = $(".getFields").map(function(){
                            //  return $(this).attr("name"));
                            //    }).get().join();
                            //
                            //

                            //clear saved objects
                            var body_data = $("body").data();
                            var collect_data_id = [];
                            $(".setObject").each(function(eqi) {
                                var this_id = $(this).attr("data-object-id");
                                if (body_data[this_id]) {
                                    var temp = {};
                                    temp[this_id] = body_data[this_id];
                                    collect_data_id.push(temp);
                                }
                            });
                            $.each(body_data, function(index, value) {
                                if ($.isNumeric(String(index))) {
                                    delete body_data[index];
                                }
                            })
                            $.each(collect_data_id, function(index, value) {
                                $.extend(body_data, collect_data_id[index])
                            });
                            // console.log("ETO NA")
                            // console.log(body_data)
                            $("body").data(body_data) //END OF CLEARING THE SAVED OBJECTS

                            $(".getFields").each(function() {
                                //return $(this).attr("name"));
                                form_Fields_Arr.push({
                                    fieldName: $(this).attr('name'),
                                    fieldType: $(this).attr('data-type')
                                });
                            })
                            //console.log(form_fields)

                            // Get Button
                            var btnName = $(".setObject_btn").map(function() {
                                return $(this).children("[data-type='button']").val();
                            }).get().join();
                            // var btnName = $(".setObject_btn").map(function(){
                            //     return $(this).children().attr("name");
                            // }).get().join();

                            // Get Workspace Content
                            var workspace_content = $(".workspace").html();
                            var formId = $('#FormId').val();
                            var btnContent = $(".btn_content").html();

                            //console.log(btnName)
                            // Set JSON
                            var workspace = {};
                            workspace["Title"] = workspace_title;
                            workspace["DisplayName"] = workspace_displayName;
                            workspace["Prefix"] = workspace_prefix;
                            workspace["Type"] = workspace_type;
                            workspace["WorkspaceHeight"] = workspace_height;
                            workspace["WorkspaceWidth"] = workspace_width;
                            workspace['BtnLength'] = btn_length;
                            workspace['BtnName'] = btnName;
                            workspace['button_content'] = btnContent;
                            workspace['ObjectLength'] = object_length;
                            workspace['WorkspaceContent'] = workspace_content;
                            workspace['form_json'] = $("body").data();
                            workspace['form_fields'] = JSON.stringify(form_Fields_Arr);
                            workspace['categoryName'] = workspace_categoryname;
                            var json_a = $("body").data();

                            if (typeof json_a.saving_request_format != "undefined") {
                                workspace['MobileJsonData'] = JSON.stringify(json_a.saving_request_format);
                            } else {
                                workspace['MobileJsonData'] = "";
                            }

                            if (typeof json_a.saved_mobile_content != "undefined") {
                                workspace['MobileContent'] = json_a.saved_mobile_content;
                            } else {
                                workspace['MobileContent'] = "";
                            }
                            /*collecting existing fields on the form*/
                            workspace['existing_fields'] = [];
                            $(".setObject").each(function(eqi_setObj) {
                                if (
                                        $(this).attr("data-type") == "labelOnly" ||
                                        $(this).attr("data-type") == "createLine" ||
                                        $(this).attr("data-type") == "table" ||
                                        $(this).attr("data-type") == "tab-panel" ||
                                        $(this).attr("data-type") == "listNames"
                                        ) {
                                    return true; //preventing to insert it to the database
                                }
                                counted_id = $(this).attr("data-object-id");
                                if ($(this).find(".getFields_" + counted_id).attr("name")) {
                                    workspace['existing_fields'].push($(this).find(".getFields_" + counted_id).attr("name").replace("[]", ""));
                                }
                            });
                            workspace['existing_fields'] = workspace['existing_fields'].join(",");
                            /*collecting existing fields on the form*/

                            //form / request privacy
                            if (json_a['form-authors']) {
                                workspace['form_authors'] = JSON.stringify(json_a['form-authors']);
                            }

                            if (json_a['form-readers']) {
                                workspace['form_viewers'] = JSON.stringify(json_a['form-readers']);
                            }

                            if (json_a['form-admin']) {
                                var form_admin = json_a['form-admin'];
                                if (form_admin != "0") {
                                    if (form_admin['departments'].length == 0 && form_admin['positions'].length == 0 && form_admin['users'].length == 0) {
                                        workspace['form-admin'] = "0";
                                        json_a['form-admin'] = "0";
                                    } else {
                                        workspace['form-admin'] = JSON.stringify(json_a['form-admin']);
                                    }
                                } else {
                                    workspace['form-admin'] = "0";
                                    json_a['form-admin'] = "0";
                                }

                            } else {
                                json_a['form-admin'] = "0";
                                workspace['form-admin'] = "0";
                            }

                            if (typeof workspace.form_json != "undefined") {
                                if (typeof workspace.form_json.manage_field_component_on_form != "undefined") {
                                    delete workspace.form_json.manage_field_component_on_form;
                                }
                                if (typeof workspace.form_json.manage_saved_ui_mobile != "undefined") {
                                    delete workspace.form_json.manage_saved_ui_mobile;
                                }
                            }
                            var json_encode = JSON.stringify(workspace);
                            //console.log(json_encode)
                            $.post("/ajax/formbuilder", {
                                action: "saveWorkspace",
                                json_encode: json_encode,
                                formId: formId
                            }, function(data) {
                                console.log(data)
                                if (data) {
                                    data = JSON.parse(data)
                                    showNotification({
                                        message: data['message'],
                                        type: data['status'],
                                        autoClose: true,
                                        duration: 3
                                    });
                                    if (data['status'] == "success") {
                                        $("#popup_overlay,#popup_container").remove();
                                        bind_onBeforeOnload(0)
                                        console.log(data)
                                        if(typeof data["saved_form_id"] != "undefined"){
                                            setTimeout(function(){
                                                window.location.replace("/formbuilder?formID="+data["saved_form_id"]+"&view_type=edit");    
                                            },3000);
                                        }
                                    }
                                    $(".saveFormLoad").hide();
                                }
                            })
                        }
                        break;

                }
            } else {
                $("#popup_overlay").remove();
                $("#popup_container").remove();
                showNotification({
                    message: "Please fix all invalid first before saving!",
                    type: "error",
                    autoClose: true,
                    duration: 5
                });
            }
        });
    },
    load_workspace_state: function() {
        var pathname = window.location.pathname;
        if (pathname == "/formbuilder" || pathname == "/generate") {
            $(".workspace.formbuilder_ws").droppable({
                accept: ".setObject",
                drop: function(e, ui) {
                    drop_top = $(document).scrollTop();
                    drop_left = $(document).scrollLeft();
                    //comment for reference use
                    //evtarget = (window.event) ? window.event.srcElement /* for IE */ : e.target;
                    //console.log(e.target)
                    //console.log(ui.draggable[0].parentElement);
                    var target = e.target;
                    var source = ui.draggable[0].parentElement;
                    if (target === source) { //conditional purpose to prevent dropping off the same place
                        //alert('Same droppable container');
                    } else {
                        if ($(this).children(".td-relative").eq(0).length == 0) {
                            $(ui.helper).appendTo(this);
                            $(ui.helper).css({
                                "top": (drop_top) + "px",
                                "left": (drop_left) + "px"
                            });
                        } else {
                            $(ui.helper).appendTo($(this).children(".td-relative").eq(0));
                            $(ui.helper).css({
                                "top": (drop_top) + "px",
                                "left": (drop_left) + "px"
                            });
                        }
                    }
                    $(ui.helper).draggable("option", "containment", "parent");
                }
            }).on({
                "click": function(evs) {
                    // alert(13245)
                    //console.log($(evs.toElement).closest(".element"));
                    target = (window.event) ? window.event.srcElement /* for IE */ : evs.target;
                    // console.log($(target).closest(".element").length);
                    if ($(target).closest(".setObject").length >= 1) { //has a parent named class
                        //walang gagawin
                    } else if ($(".dynamic-td-droppable-selected").length >= 1) {
                        $(".dynamic-td-droppable-selected").removeClass("dynamic-td-droppable-selected");
                    }
                    if ($(target).closest(".setObject").length >= 1) {
                        //walang gagawin
                    } else {
                        $(".component-primary-focus").removeClass("component-primary-focus");
                        $(".component-ancillary-focus").removeClass("component-ancillary-focus");
                    }
                }
            });

            $(".dynamic-td-droppable-selected").removeClass("dynamic-td-droppable-selected");
            if ($("#FormId").val() != 0) {
                var json = $(".form-workspace-json").text();
                if (json != "") {
                    //console.log(json)
                    var form_json = JSON.parse(json);
                    $("body").data(form_json['form_json']);
                }
                if ($(".workspace.formbuilder_ws").find(".setObject").length >= 1) {
                    if (form_json.WorkspaceWidth) {
                        $(".form_size_width").val(form_json.WorkspaceWidth);
                        $(".form_size_height").val(form_json.WorkspaceHeight);
                        $(".workspace.formbuilder_ws").css({
                            "width": (form_json.WorkspaceWidth) + "px",
                            "height": (form_json.WorkspaceHeight) + "px"
                        });
                    }

                    /*removing excess ui's and classes*/
                    $(".ui-resizable").removeClass("ui-resizable");
                    $(".ui-resizable-handle").remove();
                    $(".setObject-drag-handle").remove(); // ADDED 12 2 2013
                    $(".component-ancillary-focus").removeClass("component-ancillary-focus");
                    $(".component-primary-focus").removeClass("component-primary-focus");

                    /*getting counts and making the objects on the form functional*/
                    var countings = [];

                    /*TAB PANEL*/
                    $(".form-tabbable-pane").each(function(eqi_tab_panel) {
                        countings.push(parseInt($(this).closest(".setObject").attr("data-object-id")));
                        dragObects($(this).closest(".setObject"), ".workspace", $(".form_set_size.form_size_height").val(), $(this).closest(".setObject").attr("data-object-id"));
                        $(this).find(".li-add-new-tab-panel").remove();
                        $(this).tabPanel({
                            resizableContent: true,
                            resizableContentContainment: ".workspace.formbuilder_ws"
                        });
                    });

                    /*TABLE*/
                    $(".form-table").each(function() {
                        countings.push(parseInt($(this).closest(".setObject").attr("data-object-id")));
                        dragObects($(this).closest(".setObject"), ".workspace", $(".form_set_size.form_size_height").val(), $(this).closest(".setObject").attr("data-object-id"));
                        if ($(this).closest(".table-wrapper").length >= 1) {
                            $(this).closest(".table-wrapper").find(".table-actions-ra").remove();
                            $(this).find(".dynamic-td-droppable-selected").removeClass("dynamic-td-droppable-selected");
                            $(this).removeClass(".thisDynamicTable");
                            $(this).unwrap();
                            $(this).dynamicTable({
                                "tableBorder": "1",
                                "tHeadTag": false,
                                droppableCell: true,
                                cellDroppable: {
                                    accept: ".setObject",
                                    revert: true,
                                    greedy: true,
                                    drop: function(e, ui) {
                                        //comment for reference use
                                        //evtarget = (window.event) ? window.event.srcElement /* for IE */ : e.target;
                                        //console.log(e.target)
                                        //console.log(ui.draggable[0].parentElement);
                                        if ($(ui.helper).find(".form-table").length == 0 && $(ui.helper).find(".form-tabbable-pane").length == 0) {
                                            var target = e.target;
                                            var source = ui.draggable[0].parentElement;
                                            if (target === source) { //conditional purpose to prevent dropping off the same place
                                                //alert('Same droppable container');
                                            } else {
                                                if ($(this).children(".td-relative").eq(0).length == 0) {
                                                    $(ui.helper).appendTo(this);
                                                    $(ui.helper).css({
                                                        "top": "0px",
                                                        "left": "0px"
                                                    });
                                                } else {
                                                    $(ui.helper).appendTo($(this).children(".td-relative").eq(0));
                                                    $(ui.helper).css({
                                                        "top": "0px",
                                                        "left": "0px"
                                                    });
                                                }

                                            }
                                            if ($(ui.helper).outerWidth() > $(this).outerWidth()) {
                                                ung_padding_left = $(ui.helper).css("padding-left").split("px").join("");
                                                ung_padding_right = $(ui.helper).css("padding-right").split("px").join("");
                                                draggable_ele_width = $(ui.helper).outerWidth();
                                                if ($(this).hasClass("ui-droppable")) {
                                                    dis_tr_index = $(this).closest("tr").index();
                                                    if ($(this).prop("tagName") == "TD") {
                                                        dis_td_index = $(this).index();
                                                    } else {
                                                        dis_td_index = $(this).closest("td.ui-resizable").index();
                                                    }
                                                    $(this).closest("tbody").children("tr").each(function() {
                                                        $(this).children("td.ui-resizable").eq(dis_td_index).css({
                                                            "width": draggable_ele_width
                                                        });
                                                        $(this).children("td.ui-resizable").eq(dis_td_index).resizable({
                                                            "minWidth": draggable_ele_width
                                                        });
                                                    });
                                                }
                                            }
                                            if ($(ui.helper).outerHeight() > $(this).outerHeight()) {
                                                ung_padding_top = $(ui.helper).css("padding-top").split("px").join("");
                                                ung_padding_bottom = $(ui.helper).css("padding-bottom").split("px").join("");
                                                draggable_ele_height = $(ui.helper).outerHeight();
                                                if ($(this).hasClass("ui-droppable")) {
                                                    $(this).closest("tr").children("td.ui-resizable").css({
                                                        "height": draggable_ele_height
                                                    });
                                                    $(this).closest("tr").children("td.ui-resizable").resizable({
                                                        "minHeight": draggable_ele_height
                                                    });
                                                }
                                            }
                                        }
                                        $(ui.helper).draggable("option", "containment", "parent");
                                    }
                                }
                            }).css({
                                "border": "none"
                            });
                            if ($(this).attr("repeater-table") == "true") {
                                $(this).closest(".table-wrapper").find(".table-actions-ra.action-row-add").hide();
                            }
                        }
                    });
                    //making objects draggable
                    $('.setObject[data-object-id]').each(function(eqi_setObj) {
                        if ($(this).find(".form-table").length >= 1 || $(this).find(".form-tabbable-pane").length >= 1) {
                            return true;
                        }
                        countings.push(parseInt($(this).attr("data-object-id")));
                        dragObects($(this), ".workspace", $(".form_set_size.form_size_height").val(), $(this).attr("data-object-id"));

                        //set the default values of checkbox and radio
                        var object_id = $(this).attr("data-object-id");
                        var frm_json = $("body").data();
                        if (
                                ($(this).find(".getFields_" + object_id).attr("type") == "radio" || $(this).find(".getFields_" + object_id).attr("type") == "checkbox") &&
                                $(this).find(".getFields_" + object_id).prop("tagName") == "INPUT"
                                ) {
                            var self = $(this);
                            if (typeof frm_json[object_id] != "undefined") {
                                if (typeof frm_json[object_id].defaultValues != "undefined") {
                                    $.each(frm_json[object_id].defaultValues, function(index, item) {
                                        var string_value = frm_json[object_id].defaultValues[index];
                                        if (
                                                self.find(".getFields_" + object_id).eq(index).length >= 1 &&
                                                self.find(".getFields_" + object_id).eq(index).val() == string_value
                                                ) {
                                            self.find(".getFields_" + object_id).eq(index).prop("checked", true);
                                        }
                                    });
                                }
                            }
                        } else if ($(this).find(".getFields_" + object_id).prop("tagName") == "SELECT") {
                            var self = $(this);
                            if (typeof frm_json[object_id] != "undefined") {
                                if (typeof frm_json[object_id].defaultValues != "undefined") {
                                    $.each(frm_json[object_id].defaultValues, function(index, item) {
                                        var string_value = frm_json[object_id].defaultValues[index];
                                        if (
                                                self.find(".getFields_" + object_id).children("option").eq(index).length >= 1 &&
                                                self.find(".getFields_" + object_id).children("option").eq(index).val() == string_value
                                                ) {
                                            self.find(".getFields_" + object_id).children("option").eq(index).prop("selected", true);
                                        }

                                    })
                                }
                            }
                        }
                    });
                    countings = countings.sort(function(a, b) {
                        return b - a
                    }); //getting how many objects created on the form and sort this variable to know what is the total countings
                    count = countings[0];
                    count++;
                    /*getting counts and making the objects on the form functional*/
                }
            } else {
                //new form

                RequestPivacy.defaultChecked();
            }

        }

    }
}

$(document).ready(function() {
    $(document).on({
        "keydown": function() {

        }
    })
    var patname = window.location.pathname;
    if (patname == "/formbuilder") {
        $(".formbuilder_objects").perfectScrollbar();
        $(".ps-scrollbar-x").remove();
    }

    // OOP JS Functions Call

    /* Main Workspace */
    workspace_functions.view_save(".save_workspace");

    /* Main Formbuilder */

    form_settings_get_objects.get_objects(".getObjects");
    form_settings_get_objects.delete_objects(".object_remove");
    form_settings_get_objects.clear_all(".clear_all_formbuilder_workspace");
    form_settings_get_objects.form_size(".form_size");
    form_settings_get_objects.form_set_size(".form_set_size");
    form_settings_get_objects.save_form_workspace(".save_form_workspace");

    /*initialization startup load of the workspace*/

    form_settings_get_objects.load_workspace_state();

    if ($(".workspace.formbuilder_ws").find(".setObject").length >= 1) {
        if (checkFormMinWidth() != null) {
            $(".workspace.formbuilder_ws").css({
                "min-width": checkFormMinWidth()
            });
        }
        if (checkFormMinHeight() != null) {
            $(".workspace.formbuilder_ws").css({
                "min-height": checkFormMinHeight()
            });
        }
    }
    //resizeForm(".formbuilder_page"); // Resize Form
    // Control Save Workspace
    control_save_workspace(".save_workspace");

    // Hide / Show Properties of objects
    prop_hovering();

    //set form properties on json
    setFormProperties();

    picklist.init();

    // if(document.URL.indexOf("formbuilder") >= 0){
    $(".f-show-ruler[name='show-form-ruler-select']").on({
        "change": function(e) {
            //alert($(this).val())
            selected_val_show = $(this).val();
            if (selected_val_show == "yes") {
                // if($(".topPointerRuler-container").length >= 1){
                // 	$(".topPointerRuler-container").show();
                // }
                // if($(".leftPointerRuler-container").length >= 1){
                // 	$(".leftPointerRuler-container").show();
                // }
                if ($(".dragging-static-ruler.top").length == 0) {
                    tooltip_ele_top = $("<span class='dragging-static-ruler top'></span>")
                    $("body").append(tooltip_ele_top);
                    tooltip_ele_top.css({
                        "position": "absolute",
                        //"font-weight":"bold",
                        "font-size": "15px",
                        "color": "white",
                        "background-color": "rgba(0,0,0,0.25)",
                        "border": "1px solid rgba(0,0,0,0.5)",
                        "padding": (1) + "px"
                    });
                    $(".topPointerRuler-tip").draggable("option", "tooltip_ele_top", tooltip_ele_top);
                    tooltip_ele_top.html($(".topPointerRuler-tip").position().left + 5)
                    tooltip_ele_top.css({
                        "top": ($(".topPointerRuler-tip").offset().top - $(tooltip_ele_top).outerHeight()) + "px",
                        "left": ($(".topPointerRuler-tip").offset().left) + "px"
                    })
                    the_ruler_top = $("<div class='form-builder-ruler vertical' style='z-index:100;'></div>");
                    $(".workspace.formbuilder_ws,.workspace.workflow_ws,.workspace.orgchart_ws").append(the_ruler_top);
                    the_ruler_top.css({
                        "position": "absolute",
                        "background-color": "blue",
                        "width": (1) + "px",
                        "height": "100%",
                        "left": ($(".topPointerRuler-tip").position().left + 5) + "px"
                    });
                    $(".topPointerRuler-tip").draggable("option", "formbuilder_ruler_vertical", the_ruler_top);
                    the_ruler_top.draggable({
                        snap: ".setObject, .form-builder-ruler",
                        snapTolerance: 3,
                        disabled: true,
                        snapMode: "outer"
                    });
                }

                if ($(".dragging-static-ruler.left").length == 0) {
                    tooltip_ele_left = $("<span class='dragging-static-ruler left'></span>")
                    $("body").append(tooltip_ele_left);
                    tooltip_ele_left.css({
                        "position": "absolute",
                        //"font-weight":"bold",
                        "font-size": "15px",
                        "color": "white",
                        "background-color": "rgba(0,0,0,0.25)",
                        "border": "1px solid rgba(0,0,0,0.5)",
                        "padding": (1) + "px"
                    });
                    $(".leftPointerRuler-tip").draggable("option", "tooltip_ele_left", tooltip_ele_left);
                    tooltip_ele_left.html($(".leftPointerRuler-tip").position().top + 5)
                    tooltip_ele_left.css({
                        "top": ($(".leftPointerRuler-tip").offset().top) + "px",
                        "left": ($(".leftPointerRuler-tip").offset().left - $(tooltip_ele_left).outerWidth()) + "px"
                    })


                    the_ruler_left = $("<div class='form-builder-ruler horizontal' style='z-index:100;'></div>");
                    $(".workspace.formbuilder_ws,.workspace.workflow_ws,.workspace.orgchart_ws").append(the_ruler_left);
                    the_ruler_left.css({
                        "position": "absolute",
                        "background-color": "blue",
                        "width": "100%",
                        "height": (1) + "px",
                        "top": ($(".leftPointerRuler-tip").position().top + 5) + "px"
                    });
                    $(".leftPointerRuler-tip").draggable("option", "formbuilder_ruler_horizontal", the_ruler_left);
                    the_ruler_left.draggable({
                        snap: ".setObject, .form-builder-ruler",
                        snapTolerance: 3,
                        disabled: true,
                        snapMode: "outer"
                    });
                }
            } else if (selected_val_show == "no") {
                // if($(".topPointerRuler-container").length >= 1){
                // 	$(".topPointerRuler-container").hide();
                // }
                // if($(".leftPointerRuler-container").length >= 1){
                // 	$(".leftPointerRuler-container").hide()
                // }
                if ($(".dragging-static-ruler").length >= 1) {
                    $(".dragging-static-ruler").remove();
                }
                if ($(".form-builder-ruler").length >= 1) {
                    $(".form-builder-ruler").remove();
                }
            }
        }


    });
    function checkStaticRulerTop(rulertip_ele) {// Top (target left)
        mostleft = $(rulertip_ele).position().left + $(rulertip_ele).width();
        try {
            $(".workspace.formbuilder_ws.ui-resizable,.workspace.workflow_ws.ui-resizable,.workspace.orgchart_ws.ui-resizable").resizable({
                "minWidth": mostleft
            });
        } catch (error) {
            console.log("error on function checkStaticRulerTop( maybe due to uninitialized resizable");
        }
    }
    function checkStaticRulerLeft(rulertip_ele) {// left (target top)
        mostbottom = $(rulertip_ele).position().top + $(rulertip_ele).height();
        try {
            $(".workspace.formbuilder_ws.ui-resizable,.workspace.workflow_ws.ui-resizable,.workspace.orgchart_ws.ui-resizable").resizable({
                "minHeight": mostbottom
            });
        } catch (error) {
            console.log("error on function checkStaticRulerLeft( maybe due to uninitialized resizable");
        }
    }
    // Top (target left)
    $(".topPointerRuler-tip").draggable({
        containment: ".topPointerRuler-container",
        zIndex: 100,
        start: function(event, ui) {
            if ($(".dragging-static-ruler.top").length == 0) {
                tooltip_ele_top = $("<span class='dragging-static-ruler top'></span>")
                $("body").append(tooltip_ele_top);
                tooltip_ele_top.css({
                    "position": "absolute",
                    //"font-weight":"bold",
                    "font-size": "15px",
                    "color": "white",
                    "background-color": "rgba(0,0,0,0.25)",
                    "border": "1px solid rgba(0,0,0,0.5)",
                    "padding": (1) + "px"
                });
                $(ui.helper).draggable("option", "tooltip_ele_top", tooltip_ele_top);
            }
            if ($(".form-builder-ruler.vertical").length == 0) {
                if ($(".f-show-ruler").val() == "yes") {
                    the_ruler = $("<div class='form-builder-ruler vertical'></div>");
                    $(".workspace.formbuilder_ws,.workspace.workflow_ws,.workspace.orgchart_ws").append(the_ruler);
                    the_ruler.css({
                        "position": "absolute",
                        "background-color": "blue",
                        "width": (1) + "px",
                        "height": "100%"
                    });
                    $(ui.helper).draggable("option", "formbuilder_ruler_vertical", the_ruler);
                    the_ruler.draggable({
                        snap: ".setObject, .form-builder-ruler",
                        snapTolerance: 3,
                        disabled: true,
                        snapMode: "outer"
                    });
                }
            }
        },
        drag: function(event, ui) {
            if ($(ui.helper).draggable("option", "tooltip_ele_top").length >= 1) {
                tooltip_ele_top = $(ui.helper).draggable("option", "tooltip_ele_top");
                $(tooltip_ele_top).html(ui.position.left + 5);
                $(tooltip_ele_top).css({
                    "left": (ui.offset.left) + "px",
                    "top": (ui.offset.top - $(tooltip_ele_top).outerHeight()) + "px"
                });
            }
            if ($(ui.helper).draggable("option", "formbuilder_ruler_vertical").length >= 1) {
                formbuilder_ruler_vertical = $(ui.helper).draggable("option", "formbuilder_ruler_vertical");
                formbuilder_ruler_vertical.css({
                    "left": (ui.position.left + 5) + "px"
                })
            }
        },
        stop: function(event, ui) {
            try {
                if ($(".f-show-ruler:checked[name='show-form-ruler-select']").val() == "yes") {
                } else {
                    if ($(ui.helper).draggable("option", "tooltip_ele_top").length >= 1) {
                        $(ui.helper).draggable("option", "tooltip_ele_top").remove();
                    }
                    if ($(ui.helper).draggable("option", "formbuilder_ruler_vertical").length >= 1) {
                        $(ui.helper).draggable("option", "formbuilder_ruler_vertical").remove();
                    }
                }
                $(".workspace.formbuilder_ws.ui-resizable,.workspace.workflow_ws.ui-resizable,.workspace.orgchart_ws.ui-resizable").resizable({
                    "minWidth": (ui.position.left + $(ui.helper).width())
                });
            } catch (error) {
                console.log("error on drag of .topPointerRuler-tip")
            }
            //checkStaticRulerTop($(ui.helper));
        }
    })
    $(".topPointerRuler-container").on({
        "click": function(e) {
            var target = (window.event) ? window.event.srcElement /* for IE */ : e.target;
            if ($(target).hasClass("topPointerRuler-tip")) {

            } else {
                var positionX = e.offsetX;
                $(this).children(".topPointerRuler-tip").css({
                    "left": (positionX - 5) + "px"
                });
                if ($(".form-builder-ruler.vertical").length >= 1) {
                    $(".form-builder-ruler.vertical").css({
                        "left": (positionX) + "px"
                    });
                }
                if ($(".dragging-static-ruler.top").length >= 1) {
                    $(".dragging-static-ruler.top").css({
                        "left": ($(this).children(".topPointerRuler-tip").offset().left) + "px"
                    });
                    $(".dragging-static-ruler.top").html($(this).children(".topPointerRuler-tip").position().left)
                }
            }
        }
    })

    // Left (target top)
    $(".leftPointerRuler-tip").draggable({
        containment: ".leftPointerRuler-container",
        zIndex: 100,
        start: function(event, ui) {
            if ($(".dragging-static-ruler.left").length == 0) {
                tooltip_ele_left = $("<span class='dragging-static-ruler left'></span>")
                $("body").append(tooltip_ele_left);
                tooltip_ele_left.css({
                    "position": "absolute",
                    //"font-weight":"bold",
                    "font-size": "15px",
                    "color": "white",
                    "background-color": "rgba(0,0,0,0.25)",
                    "border": "1px solid rgba(0,0,0,0.5)",
                    "padding": (1) + "px"
                });
                $(ui.helper).draggable("option", "tooltip_ele_left", tooltip_ele_left);
            }
            if ($(".form-builder-ruler.horizontal").length == 0) {
                if ($(".f-show-ruler").val() == "yes") {
                    the_ruler = $("<div class='form-builder-ruler horizontal'></div>");
                    $(".workspace.formbuilder_ws,.workspace.workflow_ws,.workspace.orgchart_ws").append(the_ruler);
                    the_ruler.css({
                        "position": "absolute",
                        "background-color": "blue",
                        "width": "100%",
                        "height": (1) + "px"
                    });
                    $(ui.helper).draggable("option", "formbuilder_ruler_horizontal", the_ruler);
                    the_ruler.draggable({
                        snap: ".setObject, .form-builder-ruler",
                        snapTolerance: 3,
                        disabled: true,
                        snapMode: "outer"
                    });
                }
            }
        },
        drag: function(event, ui) {
            if ($(ui.helper).draggable("option", "tooltip_ele_left").length >= 1) {
                tooltip_ele_left = $(ui.helper).draggable("option", "tooltip_ele_left");
                $(tooltip_ele_left).html(ui.position.top + 5);
                $(tooltip_ele_left).css({
                    "left": (ui.offset.left - $(tooltip_ele_left).outerWidth()) + "px",
                    "top": (ui.offset.top) + "px"
                });
            }
            if ($(ui.helper).draggable("option", "formbuilder_ruler_horizontal").length >= 1) {
                formbuilder_ruler_horizontal = $(ui.helper).draggable("option", "formbuilder_ruler_horizontal");
                formbuilder_ruler_horizontal.css({
                    "top": (ui.position.top + 5) + "px"
                })
            }
        },
        stop: function(event, ui) {
            try {
                if ($(".f-show-ruler:checked[name='show-form-ruler-select']").val() == "yes") {
                } else {
                    if ($(ui.helper).draggable("option", "tooltip_ele_left").length >= 1) {
                        $(ui.helper).draggable("option", "tooltip_ele_left").remove();
                    }
                    if ($(ui.helper).draggable("option", "formbuilder_ruler_horizontal").length >= 1) {
                        $(ui.helper).draggable("option", "formbuilder_ruler_horizontal").remove();
                    }
                }


                $(".workspace.formbuilder_ws.ui-resizable,.workspace.workflow_ws.ui-resizable,.workspace.orgchart_ws.ui-resizable").resizable({
                    "minHeight": (ui.position.top + $(ui.helper).height())
                });
            } catch (error) {
                console.log("error on drag of .leftPointerRuler-tip")
            }
            //checkStaticRulerLeft($(ui.helper))
        }
    })
    $(".leftPointerRuler-container").on({
        "click": function(e) {
            var target = (window.event) ? window.event.srcElement /* for IE */ : e.target;
            if ($(target).hasClass("leftPointerRuler-tip")) {

            } else {
                var positionY = e.offsetY;
                $(this).children(".leftPointerRuler-tip").css({
                    "top": (positionY - 5) + "px"
                });
                if ($(".form-builder-ruler.horizontal").length >= 1) {
                    $(".form-builder-ruler.horizontal").css({
                        "top": (positionY) + "px"
                    });
                }
                if ($(".dragging-static-ruler.left").length >= 1) {
                    $(".dragging-static-ruler.left").css({
                        "top": ($(this).children(".leftPointerRuler-tip").offset().top) + "px"
                    });
                    $(".dragging-static-ruler.left").html($(this).children(".leftPointerRuler-tip").position().top)
                }
            }
        }
    })
    // }else{
    // 	$(".f-show-ruler[name='show-form-ruler-select']").hide()
    // 	$(".topPointerRuler-container").hide();
    // 	$(".leftPointerRuler-container").hide()
    // 	$(".form-main-ruler-nav-control").hide();
    // }

    // Set Value of the Object Properties On Text Field
    $("body").on("keyup", "input.obj_prop,textarea.obj_prop", function() {
        //get property type
        var data_properties_type = $(this).attr("data-properties-type");
        var value = $(this).val();
        var json = $("body").data();
        var objID = $(this).attr("data-object-id");
        if (json['' + objID + '']) {
            var prop_json = json['' + objID + ''];
        } else {
            var prop_json = {};
        }
        // Change Properties of the selected objects
        switch (data_properties_type) {
            case "lblName":
                var lblName = $(this).val();
                $("#lbl_" + objID).html(lblName);
                break;
            case "lblFldName":
                var lblFldName = $(this).val();
                var data_type = $(this).attr("data-type");

                switch (data_type) {
                    case "button":
                        $("#btnName_" + objID).attr("name", lblFldName.replace(/ /g, ''));
                        $("#btnName_" + objID).val(lblFldName);
                        break;
                    case "checkbox":
                        lblFldName = lblFldName + "[]";
                        $(".getFields_" + objID).attr("name", lblFldName.replace(/ /g, ''));
                    default:
                        $(".getFields_" + objID).attr("name", lblFldName.replace(/ /g, ''));
                        break;
                }

                break;
            case "lblPlaceHolder":
                var lblPlaceHolder = $(this).val();
                $("#getFields_" + objID).attr("placeholder", lblPlaceHolder);
                break;
            case "lblTooltip":
                var lblTooltip = $(this).val();
                $("#getFields_" + objID).attr("data-original-title", lblTooltip);
                $("#getFields_" + objID).attr("title", lblTooltip);
                break;
            case "lblMaxLength":
                var lblMaxLength = $(this).val();
                $("#getFields_" + objID).attr("maxlength", lblMaxLength);
                break;
            case "lblFieldHeight":
                var lblFieldHeight = $(this).val();
                $("#getFields_" + objID).css("height", lblFieldHeight);
                if ($("#getFields_" + objID).prop("tagName") == "TEXTAREA") {
                    $("#getFields_" + objID).closest(".setObject").css({"height": ($("#getFields_" + objID).closest(".setObject").outerHeight()) + "px"})
                    $("#getFields_" + objID).css({"height": "100%"})
                }
                break;
            case "lblFieldWidth":
                var lblFieldWidth = $(this).val();
                $("#getFields_" + objID).css("width", lblFieldWidth);
                break;
            case "lblChoices":
                var lblChoices = $(this).val();
                var data_type = $(this).attr("data-type");
                var select = "";
                var type = "";
                var eachLine = lblChoices.split('\n');
                switch (data_type) {
                    case "checkbox":
                        type = "checkbox";
                        var checkbox_name = 'checkbox_' + objID + '[]';
                        var field_name = $("[data-properties-type='lblFldName']").val();
                        if (field_name) {
                            checkbox_name = field_name + "[]";
                        }

                        var rc_align_type = $("#setObject_" + objID).attr("rc-align-type");
                        var rc_elem_alignment = "";
                        if (rc_align_type == "vertical") {
                            rc_elem_alignment = '<span class="rc-prop-alignment rc-align-vertical"></span>';
                        } else if (rc_align_type == "horizontal") {
                            rc_elem_alignment = '<span class="rc-prop-alignment rc-align-horizontal"></span>';
                        }
                       
                        for (var i = 0, l = eachLine.length; i < l; i++) {
                            select += '<label><input type="' + type + '" data-type="longtext" disabled="disabled" name="' + checkbox_name + '" class="getFields getFields_' + objID + '" id="getFields_' + objID + '" value="' + eachLine[i] + '"/>' + eachLine[i] + '</label>' + rc_elem_alignment;
                        }
                        this_select = $(select)
                        var allow_label_rc_ele = $('[data-properties-type="lblAllowLabel-RC"]');
                        var element_c_temporary = "";
                        //wrap
                        //<span class="checkbox-input-label">
                        this_select.contents().each(function(){
                            if($(this).prop("tagName")!="INPUT" || $(this).prop("tagName") == "SPAN"){
                                $(this).wrap('<span class="checkbox-input-label"/>');
                            }
                        })
                        $("#obj_fields_" + objID).html(element_c_temporary = this_select.clone());
                        if(allow_label_rc_ele.val() == "Yes"){
                            $("#obj_fields_" + objID).find(".checkbox-input-label").show();
                           //  element_c_temporary.each(function(){
                           //      if($(this).prop("tagName") == "LABEL" ){
                           //          $(this).find(".checkbox-input-label").show();
                           //      }
                           // })
                        }else{
                            $("#obj_fields_" + objID).find(".checkbox-input-label").hide();
                           // element_c_temporary.each(function(){
                           //      if($(this).prop("tagName") == "LABEL" ){
                           //          $(this).find(".checkbox-input-label").hide();
                           //      }
                           // })
                        }
                        
                        if ($(".obj_defaultValueChoices").length >= 1) {
                            var temp_elem_clone = "";
                            $(".obj_defaultValueChoices").html(temp_elem_clone = this_select.clone());

                            $(".obj_defaultValueChoices").find(".checkbox-input-label").show();
                            // temp_elem_clone.each(function(){
                            //     if($(this).prop("tagName") == "LABEL" ){
                            //         $(this).find(".checkbox-input-label").show();
                            //     }
                            // })

                            temp_elem_clone.closest(".obj_defaultValueChoices").find(".getFields_" + objID).attr("name", "for_default_use");
                            temp_elem_clone.closest(".obj_defaultValueChoices").find(".getFields_" + objID).removeAttr("disabled");
                        }
                        break;
                    case "radioButton":
                        type = "radio";
                        var radio_name = "radio_" + objID;
                        var field_name = $("[data-properties-type='lblFldName']").val();
                        if (field_name) {
                            radio_name = field_name;
                        }
                        var rc_align_type = $("#setObject_" + objID).attr("rc-align-type");
                        var rc_elem_alignment = "";
                        if (rc_align_type == "vertical") {
                            rc_elem_alignment = '<span class="rc-prop-alignment rc-align-vertical"></span>';
                        } else if (rc_align_type == "horizontal") {
                            rc_elem_alignment = '<span class="rc-prop-alignment rc-align-horizontal"></span>';
                        }
                        for (var i = 0, l = eachLine.length; i < l; i++) {
                            select += '<label><input type="' + type + '" data-type="longtext" disabled="disabled" name="' + radio_name + '" class="getFields getFields_' + objID + '" id="getFields_' + objID + '" value="' + eachLine[i] + '"/>' + eachLine[i] + '</label>' + rc_elem_alignment;
                        }
                        this_select = $(select)
                        var allow_label_rc_ele = $('[data-properties-type="lblAllowLabel-RC"]');
                        var element_c_temporary = "";
                        //wrap
                        //<span class="checkbox-input-label">
                        this_select.contents().each(function(){
                            if($(this).prop("tagName")!="INPUT" || $(this).prop("tagName") == "SPAN"){
                                $(this).wrap('<span class="radio-input-label"/>');
                            }
                        })
                        $("#obj_fields_" + objID).html(element_c_temporary = this_select.clone());
                        if(allow_label_rc_ele.val() == "Yes"){
                            $("#obj_fields_" + objID).find(".radio-input-label").show();
                        }else{
                            $("#obj_fields_" + objID).find(".radio-input-label").hide();
                        }
                        if ($(".obj_defaultValueChoices").length >= 1) {
                            var temp_elem_clone = "";
                            $(".obj_defaultValueChoices").html(temp_elem_clone = this_select.clone());

                            temp_elem_clone.closest(".obj_defaultValueChoices").find(".getFields_" + objID).attr("name", "for_default_use");
                            temp_elem_clone.closest(".obj_defaultValueChoices").find(".getFields_" + objID).removeAttr("disabled");
                        }
                        break;
                    case "selectMany":
                        for (var i = 0, l = eachLine.length; i < l; i++) {
                            select += '<option value="' + eachLine[i] + '"> ' + eachLine[i] + ' </option>';
                            //select += '<input type="' + type + '" disabled="disabled" name="radio_' + objID + '" class="" id="getFields_' + objID + '"/> ' + eachLine[i] + ' <br />';
                        }
                        $("#getFields_" + objID).html(select);
                        if ($(".obj_defaultValueChoices").length >= 1) {
                            this_select = $(select);
                            $(".obj_defaultValueChoices").find(".getFields_" + objID).html(this_select);
                            this_select.closest(".obj_defaultValueChoices").find(".getFields_" + objID).attr("name", "for_default_use");
                            this_select.closest(".obj_defaultValueChoices").find(".getFields_" + objID).removeAttr("disabled");
                        }
                        break;
                    case "dropdown":
                        for (var i = 0, l = eachLine.length; i < l; i++) {
                            select += '<option value="' + eachLine[i] + '"> ' + eachLine[i] + ' </option>';
                            //select += '<input type="' + type + '" disabled="disabled" name="radio_' + objID + '" class="" id="getFields_' + objID + '"/> ' + eachLine[i] + ' <br />';
                        }
                        $("#getFields_" + objID).html(select);
                        if ($(".obj_defaultValueChoices").length >= 1) {
                            this_select = $(select)
                            $(".obj_defaultValueChoices").find(".getFields_" + objID).html(this_select);
                            this_select.closest(".obj_defaultValueChoices").find(".getFields_" + objID).attr("name", "for_default_use");
                            this_select.closest(".obj_defaultValueChoices").find(".getFields_" + objID).removeAttr("disabled");
                        }
                        break;
                }
                defaultValuesFN(objID);
                break;
            case "defaultValue":
                if ($(this).parent().find('[name="default_val"]').length >= 1) {
                    default_type = $(this).parent().find('[name="default_val"]:checked').val();
                    if (default_type == "static") {
                        $(".getFields_" + objID).attr("default-type", "static");
                        $(".getFields_" + objID).attr("default-static-value", value);
                        if (typeof json['' + objID + ''] != "undefined") {
                            json['' + objID + ''].defaultValueType = "static";
                        }
                    } else if (default_type == "computed") {
                        $(".getFields_" + objID).attr("default-type", "computed");
                        $(".getFields_" + objID).attr("default-formula-value", value);
                        if (typeof json['' + objID + ''] != "undefined") {
                            json['' + objID + ''].defaultValueType = "computed";
                        }
                    }
                }
                break;
        }
        prop_json['' + data_properties_type + ''] = value
        json['' + objID + ''] = prop_json;
        $("body").data(json);
    });
    // Set Value of the Object Properties On Combo Box
    $("body").on("change", "select.obj_prop, input[data-properties-type][type='radio'],input[data-properties-type][type='number']", function() {
        //get property type
        var data_properties_type = $(this).attr("data-properties-type");
        var value = $(this).val();
        var json = $("body").data();
        if (typeof $(this).attr("data-object-id") != "undefined") {
            var objID = $(this).attr("data-object-id");
        } else {
            var objID = $("#popup_container").attr("data-object-id");
        }

        if (json['' + objID + '']) {
            var prop_json = json['' + objID + ''];
        } else {
            var prop_json = {};
        }

        // Change Properties of the selected objects
        switch (data_properties_type) {
            case "lblFontWg":
                var lblFontWg = $(this).val();
                $("#lbl_" + objID).css("font-weight", lblFontWg);
                break;
            case "lblFontSize":
                var lblFontSize = $(this).val();
                $("#lbl_" + objID).css("font-size", lblFontSize);
                $("#lbl_" + objID).css("line-height", (Number(lblFontSize.replace("px", "")) - 1) + "px");
                break;
            case "lblAllowLabel":
                var lblAllowLabel = $(this).val();
                if (lblAllowLabel == "Yes") {
                    $("#label_" + objID).show();
                } else {
                    $("#label_" + objID).hide();
                }
                break;
            case "lblFieldType":
                var lblFieldType = $(this).val();
                $("#getFields_" + objID).attr("data-type", lblFieldType);
                $("#getFields_" + objID).attr("data-input-type", $(this).children("option:selected").attr("data-input-type"));
                break;
            case "lblAlignment":
                var lblAlignment = $(this).val();
                if (lblAlignment == "alignLeft") {
                    $("#label_" + objID).toggleClass('label_below label_basic');
                    $("#obj_fields_" + objID).toggleClass('input_position_below input_position');
                    $("#label_" + objID).removeClass("obj_label");
                    $("#label_" + objID).css("margin-top", "5px");
                    //$("#label_" + objID).resizable({"handles":"e"})
                } else {
                    $("#label_" + objID).toggleClass('label_basic label_below');
                    $("#obj_fields_" + objID).toggleClass('input_position input_position_below');
                    $("#label_" + objID).addClass("obj_label");
                    $("#label_" + objID).css("margin-top", "0px");
                }
                break;
            case "defaultValueType"://change event
                radio_val = $('[name="default_val"]:checked').val();
                // alert(radio_val+":"+objID)
                if (radio_val == "static") {
                    if ($(".getFields_" + objID).attr("default-static-value")) {
                        $(this).closest(".input_position_below").find("textarea[data-properties-type='defaultValue']")
                                .val($(".getFields_" + objID).attr("default-static-value"));
                        prop_json["defaultValue"] = $(".getFields_" + objID).attr("default-static-value");
                        json['' + objID + ''] = prop_json;

                    } else {
                        $(this).closest(".input_position_below").find("textarea[data-properties-type='defaultValue']")
                                .val("");
                        prop_json["defaultValue"] = "";
                        json['' + objID + ''] = prop_json;
                    }
                    json['' + objID + ''].defaultValueType = "static";
                    $(".getFields_" + objID).attr("default-type", "static");
                } else if (radio_val == "computed") {
                    if ($(".getFields_" + objID).attr("default-formula-value")) {
                        $(this).closest(".input_position_below").find("textarea[data-properties-type='defaultValue']")
                                .val($(".getFields_" + objID).attr("default-formula-value"));
                        prop_json["defaultValue"] = $(".getFields_" + objID).attr("default-formula-value");
                        json['' + objID + ''] = prop_json;
                    } else {
                        $(this).closest(".input_position_below").find("textarea[data-properties-type='defaultValue']")
                                .val("");
                        prop_json["defaultValue"] = "";
                        json['' + objID + ''] = prop_json;
                    }
                    json['' + objID + ''].defaultValueType = "computed";
                    $(".getFields_" + objID).attr("default-type", "computed");
                }
                break;
            case "tabIndex":
                $(".getFields_" + objID).attr("tabindex", value);
                break;
        }

        prop_json['' + data_properties_type + ''] = value
        json['' + objID + ''] = prop_json;
        $("body").data(json);
    });
    ui.unblock();
});

/*
 * Function to select what type of object 
 *  you want to add on the workspace
 *
 */

function objType(object_type, object_drop, count, container_height) {
    var drop_location = $("." + object_drop);
    // if (
    //         $(".dynamic-td-droppable-selected").length == 1 &&
    //         object_type != "tabPanel" &&
    //         object_type != "table"
    //    ) {
    //     drop_location = $(".dynamic-td-droppable-selected").children(".td-relative").eq(0);
    // } else {

    // }

    if (
            $(".f-show-ruler[name='show-form-ruler-select']:checked").val() == "yes" &&
            $(".form-builder-ruler.vertical").length >= 1 &&
            $(".form-builder-ruler.horizontal").length >= 1
            ) {
        drop_left = $(".form-builder-ruler.vertical").position().left;
        drop_top = $(".form-builder-ruler.horizontal").position().top;
    } else {
        drop_top = $(document).scrollTop();
        drop_left = $(document).scrollLeft();
    }
    var appended_ele = "";

    switch (object_type) {
        case "labelOnly":
            appended_ele = $(labelOnly(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "textbox":
            appended_ele = $(textbox(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "checkbox":
            appended_ele = $(checkbox(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "dropdown":
            appended_ele = $(dropdown(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "radioButton":
            appended_ele = $(radioButton(count, object_type))
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "textarea":
            appended_ele = $(textArea(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px",
                "width": "200px",
                "height": "100px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "selectMany":
            appended_ele = $(selectMany(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "fileUpload":
            appended_ele = $(fileUpload(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "datepicker":
            appended_ele = $(datepicker(count, object_type))
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "fullname":
            appended_ele = $(fullname(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "dateTime":
            appended_ele = $(dateTime(count, object_type))
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "website":
            appended_ele = $(website(count, object_type))
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "fullAddress":
            appended_ele = $(fullAddress(count, object_type))
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "button":
            appended_ele = $(btn(count, object_type))
            drop_location.append(appended_ele);
            $(".ws_btn_label").hide();
            dragObects($(appended_ele), drop_location, "", count);
            count++;
            break;
        case "line":
            appended_ele = $(createLine(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "listNames":
            appended_ele = $(fieldListOfNames(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "table":
            appended_ele = $(createTable(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);

            $(appended_ele).find(".form-table").dynamicTable({
                "tableBorder": "1",
                "tHeadTag": false,
                droppableCell: true,
                cellDroppable: {
                    accept: ".setObject",
                    revert: true,
                    greedy: true,
                    drop: function(e, ui) {
                        //comment for reference use
                        //evtarget = (window.event) ? window.event.srcElement /* for IE */ : e.target;
                        //console.log(e.target);
                        //console.log(ui.draggable[0].parentElement);
                        if ($(ui.helper).find(".form-table").length == 0 && $(ui.helper).find(".form-tabbable-pane").length == 0) {
                            var target = e.target;
                            var source = ui.draggable[0].parentElement;
                            if (target === source) { //conditional purpose to prevent dropping off the same place
                                //alert('Same droppable container');
                            } else {
                                if ($(this).children(".td-relative").eq(0).length == 0) {
                                    $(ui.helper).appendTo(this);
                                    $(ui.helper).css({
                                        "top": "0px",
                                        "left": "0px"
                                    });
                                } else {
                                    $(ui.helper).appendTo($(this).children(".td-relative").eq(0));
                                    $(ui.helper).css({
                                        "top": "0px",
                                        "left": "0px"
                                    });
                                }
                            }
                            if ($(ui.helper).outerWidth() > $(this).outerWidth()) {
                                ung_padding_left = $(ui.helper).css("padding-left").split("px").join("");
                                ung_padding_right = $(ui.helper).css("padding-right").split("px").join("");
                                draggable_ele_width = $(ui.helper).outerWidth();
                                if ($(this).hasClass("ui-droppable")) {
                                    dis_tr_index = $(this).closest("tr").index();
                                    if ($(this).prop("tagName") == "TD") {
                                        dis_td_index = $(this).index();
                                    } else {
                                        dis_td_index = $(this).closest("td.ui-resizable").index();
                                    }
                                    $(this).closest("tbody").children("tr").each(function() {
                                        $(this).children("td.ui-resizable").eq(dis_td_index).css({
                                            "width": draggable_ele_width
                                        });
                                        $(this).children("td.ui-resizable").eq(dis_td_index).resizable({
                                            "minWidth": draggable_ele_width
                                        });
                                    });
                                }
                            }
                            if ($(ui.helper).outerHeight() > $(this).outerHeight()) {
                                ung_padding_top = $(ui.helper).css("padding-top").split("px").join("");
                                ung_padding_bottom = $(ui.helper).css("padding-bottom").split("px").join("");
                                draggable_ele_height = $(ui.helper).outerHeight();
                                if ($(this).hasClass("ui-droppable")) {
                                    $(this).closest("tr").children("td.ui-resizable").css({
                                        "height": draggable_ele_height
                                    });
                                    $(this).closest("tr").children("td.ui-resizable").resizable({
                                        "minHeight": draggable_ele_height
                                    });
                                }
                            }
                            $(ui.helper).draggable("option", "containment", "parent");
                            if ($(ui.helper).data()) {
                                if ($(ui.helper).data().uiResizable) {
                                    $(ui.helper).resizable("option", "containment", "parent");
                                }
                            }
                        }

                    }
                }
            }).css({
                "border": "none"
            });
            count++;
            break;
        case "tabPanel":
            appended_ele = $(createTabPanel(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);

            $(appended_ele).find(".form-tabbable-pane").tabPanel({
                resizableContent: true,
                resizableContentContainment: ".workspace.formbuilder_ws"
            });
            count++;
            break;
        case "computed":
            appended_ele = $(computedField(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "embedView":
            appended_ele = $(embedView(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "pickList":
            appended_ele = $(pickList(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "requestImage":
            appended_ele = $(photos(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
        case "barCodeScanner":
            appended_ele = $(barCodeScanner(count, object_type));
            drop_location.append(appended_ele);
            $(appended_ele).css({
                "top": (drop_top) + "px",
                "left": (drop_left) + "px"
            });
            dragObects($(appended_ele), drop_location, container_height, count);
            count++;
            break;
    }
    if (
            $(".dynamic-td-droppable-selected").length == 1 &&
            object_type != "tabPanel" &&
            object_type != "table"
            ) {
        drop_location = $(".dynamic-td-droppable-selected").children(".td-relative").eq(0);
        $(appended_ele).appendTo(drop_location);
        // console.log("YYY")
        // console.log(appended_ele)
        appended_ele_width = appended_ele.outerWidth();
        appended_ele_height = appended_ele.outerHeight();
        $(".dynamic-td-droppable-selected").css({
            "width": (appended_ele_width) + "px",
            "height": (appended_ele_height) + "px"
        });
        appended_ele.css({
            "top": (0) + "px",
            "left": (0) + "px"
        });
    } else {

    }
}

function numericFunction(element) {
    //called when key is pressed in textbox
    $("body").on("keypress", element, function(e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
}


function fire_onBeforeOnload(status) {
    if (status == 0) {
        window.onbeforeunload = function() {
            // blank function do nothing
        }
    } else {
        window.onbeforeunload = function(e) {
            return 'You will lose any unsaved edits';
        };
    }
}

function resizeForm(elements, container_height, type) {

    $(elements).resizable({
        handles: 's,e',
        resize: function(event, ui) {
            //$(".formHeight").val(ui.size.height);
            $(this).css("min-height", container_height);

        },
        stop: function(event, ui) {
            // remove default height
            $(this).css("height", ui.size.height);
            if (type == "orgchart") {
                $(".form_size_width").val($(".orgchart_ws").width());
                $(".form_size_height").val($(".orgchart_ws").height());
                $(".node-drag").draggable("option", "containment", shrinkSize(".workspace", 20, 20))
            } else if (type == "workflow") {
                $(".form_size_width").val($(".workflow_ws").width());
                $(".form_size_height").val($(".workflow_ws").height());
                $(".node-drag").each(function() {
                    if ($(this).hasClass("ui-draggable")) {
                        $(this).draggable("option", "containment", shrinkSize(".workspace", 20, 20))
                    }
                })
            } else {
                $(".form_size_width").val($(".formbuilder_ws").width());
                $(".form_size_height").val($(".formbuilder_ws").height());
            }
        },
        snapMode: "Outer",
        snap: true,
    });
}

function checkFormMinWidth(type) {
    var add_padding = 13;
    var dragObjRightPosition = [];
    var classWorkspace = ".workspace.formbuilder_ws";
    if (type == "orgchart") {
        classWorkspace = ".workspace.orgchart_ws";
    } else if (type == "workflow") {
        classWorkspace = ".workspace.workflow_ws";
    }
    $(classWorkspace).children(".ui-draggable").each(function() {
        dragObjRightPosition.push(($(this).position().left) + ($(this).width()));
    });
    if (dragObjRightPosition.length >= 1) {
        var rets = dragObjRightPosition.sort(function(a, b) {
            return b - a;
        });
        return rets[0] + add_padding;
    } else {
        return null;
    }
}
function checkFormMinHeight(type) {
    var add_padding = 13;
    var dragObjBottomPosition = [];
    var rets;
    var classWorkspace = ".workspace.formbuilder_ws";
    if (type == "orgchart") {
        classWorkspace = ".workspace.orgchart_ws";
    } else if (type == "workflow") {
        classWorkspace = ".workspace.workflow_ws";
    }
    $(classWorkspace).children(".ui-draggable").each(function() {
        dragObjBottomPosition.push(($(this).position().top) + ($(this).height()));
    });
    if (dragObjBottomPosition.length >= 1) {
        rets = dragObjBottomPosition.sort(function(a, b) {
            return b - a;
        });
        return rets[0] + add_padding;
    } else {
        return null;
    }
}

function checkParentResizableMinHeight(passedObjEle) {
    var the_parent_resizable = $(passedObjEle).parents(".ui-resizable").eq(0);
    var add_padding = 0;
    var dragObjBottomPosition = [];
    try {
        if (the_parent_resizable.children(".td-relative").length >= 1) {
            the_parent_resizable.children(".td-relative").children(".ui-draggable").each(function() {
                dragObjBottomPosition.push(($(this).position().top) + ($(this).outerHeight()));
            });
        } else {
            the_parent_resizable.children(".ui-draggable").each(function() {
                dragObjBottomPosition.push(($(this).position().top) + ($(this).outerHeight()));
            });
        }
        rets = dragObjBottomPosition.sort(function(a, b) {
            return b - a;
        });
        return rets[0] + add_padding;
    } catch (error) {
        console.log("function checkParentResizableMinHeight: the resizable is not yet initialized ")
    }
}

function checkParentResizableMinWidth(passedObjEle) {
    var the_parent_resizable = $(passedObjEle).parents(".ui-resizable").eq(0);
    var add_padding = 0;
    var dragObjRightPosition = [];
    try {
        if (the_parent_resizable.children(".td-relative").length >= 1) {
            the_parent_resizable.children(".td-relative").children(".ui-draggable").each(function() {
                dragObjRightPosition.push(($(this).position().left) + ($(this).outerWidth()));
            });
        } else {
            the_parent_resizable.children(".ui-draggable").each(function() {
                dragObjRightPosition.push(($(this).position().left) + ($(this).outerWidth()));
            });
        }
        rets = dragObjRightPosition.sort(function(a, b) {
            return b - a;
        });
        return rets[0] + add_padding;
    } catch (error) {
        console.log("function checkParentResizableMinWidth: the resizable is not yet initialized ")
    }
}
function defaultValuesFN(object_id) {

    //this default value is for multiple selection options and choices
    if ($(".obj_defaultValueChoices").length >= 1) {

        json = $("body").data();
        console.log(json);

        var ele_choices_default = $($(".getFields_" + object_id).closest("#obj_fields_" + object_id + ".input_position_below").html());
        $(".obj_defaultValueChoices").html(ele_choices_default);
        if (ele_choices_default.hasClass("getFields")) {
            ele_choices_default.removeAttr("disabled");
            ele_choices_default.attr("name", "for_default_use");
        } else {
            ele_choices_default.closest(".input_position_below.obj_defaultValueChoices").find(".getFields_" + object_id).removeAttr("disabled");
            ele_choices_default.closest(".input_position_below.obj_defaultValueChoices").find(".getFields_" + object_id).attr("name", "for_default_use");
        }

        //restoring values saved settings for default value
        if (typeof json[object_id] != "undefined") {
            if (typeof json[object_id].defaultValues != "undefined") {
                if (ele_choices_default.hasClass("getFields")) {
                    $.each(json[object_id].defaultValues, function(index, item) {
                        ele_choices_default.children("option[value='" + json[object_id].defaultValues[index] + "']").eq(index).prop("selected", true);
                    })
                    if (typeof json[object_id].defaultValueType != "undefined") {
                        if ($('[data-properties-type="defaultValueType"][value="' + json[object_id].defaultValueType + '"]').length >= 1) {
                            $('[data-properties-type="defaultValueType"][value="' + json[object_id].defaultValueType + '"]').prop("checked", true);
                        }
                    }
                } else {
                    var container_radio_check = ele_choices_default.closest(".input_position_below.obj_defaultValueChoices");
                    var radio_check_buttons = container_radio_check.find(".getFields_" + object_id);
                    $.each(json[object_id].defaultValues, function(index, item) {
                        var radio_check_strvalue = json[object_id].defaultValues[index];
                        if (
                                $(radio_check_buttons).eq(index).length >= 1 &&
                                $(radio_check_buttons).eq(index).val() == radio_check_strvalue
                                ) {
                            $(radio_check_buttons).eq(index).prop("checked", true);
                        }
                    });
                    if (typeof json[object_id].defaultValueType != "undefined") {
                        if ($('[data-properties-type="defaultValueType"][value="' + json[object_id].defaultValueType + '"]').length >= 1) {
                            $('[data-properties-type="defaultValueType"][value="' + json[object_id].defaultValueType + '"]').prop("checked", true);
                        }
                    }
                }
            }
        }
        //making the functionality for default values
        // console.log("WGAGESGFDSFSA")
        // console.log(ele_choices_default)
        if (ele_choices_default.hasClass("getFields")) {
            ele_choices_default.on({
                "change": function() {
                    var json = $("body").data();
                    var object_id = $("#popup_container").attr("data-object-id");
                    //apply changes field on the form
                    $(".workspace.formbuilder_ws").find(".getFields_" + object_id).val($(this).val());
                    //saving on json
                    json[object_id] = (typeof json[object_id] == "undefined") ? {} : json[object_id];
                    json[object_id].defaultValues = (typeof json[object_id].defaultValues == "undefined") ? {} : json[object_id].defaultValues;
                    ele_choices_default.children("option").each(function(eqi_option) {
                        if ($(this).is(":selected")) {
                            json[object_id].defaultValues[eqi_option] = $(this).val();
                            json[object_id].defaultValueType = $('[data-properties-type="defaultValueType"]:checked').val();
                        } else {
                            if (typeof json[object_id].defaultValues[eqi_option] != "undefined") {
                                delete json[object_id].defaultValues[eqi_option]
                            }
                        }
                    });
                    // alert($(ele_choices_default,":checked").val())
                    // alert($(this)[0].selectedIndex)
                    // alert(ele_choices_default.children("option").eq(0).prop("selected",true));
                    // console.log($(ele_choices_default,":checked"));

                    $("body").data(json);
                    // console.log("select");
                    // console.log($("body").data());
                }
            });
        } else {
            //console.log(ele_choices_default.closest(".input_position_below.obj_defaultValueChoices"))
            var container_radio_check = ele_choices_default.closest(".input_position_below.obj_defaultValueChoices");
            var radio_check_buttons = container_radio_check.find(".getFields_" + object_id);

            radio_check_buttons.on({
                "change": function() {
                    var json = $("body").data();
                    var object_id = $("#popup_container").attr("data-object-id");
                    if ($(this).is(":checked")) {

                        //apply changes to the fields on form
                        var checked_index = radio_check_buttons.index($(this));
                        var checked_value = $(this).val();
                        $(".workspace.formbuilder_ws").find(".getFields_" + object_id).eq(checked_index).prop("checked", true);
                        //saving on json
                        json[object_id] = (typeof json[object_id] == "undefined") ? {} : json[object_id];
                        var parallel_field_on_form = $(".workspace.formbuilder_ws").find(".getFields_" + object_id)

                        parallel_field_on_form.each(function(eqi_parallel) {
                            if ($(this).is(":checked")) {
                                json[object_id].defaultValues = (typeof json[object_id].defaultValues == "undefined") ? {} : json[object_id].defaultValues;
                                json[object_id].defaultValues[checked_index] = checked_value;
                                json[object_id].defaultValueType = $('[data-properties-type="defaultValueType"]:checked').val();
                            } else {
                                //this is for radio because the radio is single value not a multiple values
                                if (radio_check_buttons.attr("type") == "radio") {
                                    if (typeof json[object_id].defaultValues != "undefined") {
                                        if (typeof json[object_id].defaultValues[eqi_parallel] != "undefined") {
                                            delete json[object_id].defaultValues[eqi_parallel]
                                        }
                                    }
                                }
                            }
                        });
                        // json[object_id].defaultValuesIndex = checked_index;
                        // json[object_id].defaultValues = checked_value;
                    } else {
                        //apply changes to the fields on the form
                        var checked_index = radio_check_buttons.index($(this));
                        var checked_value = $(this).val();
                        $(".workspace.formbuilder_ws").find(".getFields_" + object_id).eq(checked_index).prop("checked", false);
                        //saving changes onto json
                        if (typeof json[object_id] != "undefined") {
                            if (typeof json[object_id].defaultValues != "undefined") {
                                if (typeof json[object_id].defaultValues[checked_index] != "undefined") {
                                    delete json[object_id].defaultValues[checked_index]
                                }
                            }
                        }
                    }
                    $("body").data(json);
                    // console.log("radio check")
                    // console.log($("body").data())
                }
            });
        }
    }
}
function dragObects(elements, container, container_height, properties_id) {
    function checkCollisionDroppableBoundaries(this_element) {
        if ($(this_element).closest(".workspace").length == 0) {
            alert("the element is not in the droppable containment");
            return false;
        }

        // var droppable_top = 0;
        // var droppable_left = 0;
        // var droppable_right = $("#ws-container #droppable").width();
        // var droppable_bottom = $("#ws-container #droppable").height();

        var droppable_top = 0;
        var droppable_left = 0;
        var droppable_right = $(this_element).parent().width();
        var droppable_bottom = $(this_element).parent().height();

        var element_right = $(this_element).position().left + $(this_element).outerWidth();
        var element_bottom = $(this_element).position().top + $(this_element).outerHeight();

        var element_top = $(this_element).position().top;
        var element_left = $(this_element).position().left;
        // $(".ws-status-bar").html(
        //  element_right+" <= "+droppable_right+" && "+
        //  "<br/>"+element_bottom+" <= "+droppable_bottom+" && "+
        //  "<br/>"+element_top+" >= "+droppable_top+" && "+
        //  "<br/>"+element_left+" >= "+droppable_left
        // );

        if (element_right >= droppable_right) {
            $(this_element).css({
                left: droppable_right - $(this_element).outerWidth()
            });
        }
        if (element_bottom >= droppable_bottom) {
            $(this_element).css({
                top: droppable_bottom - $(this_element).outerHeight()
            });
        }
        if (element_top <= droppable_top) {
            $(this_element).css({
                top: droppable_top
            });
        }
        if (element_left <= droppable_left) {
            $(this_element).css({
                left: droppable_left
            });
        }
    }

    resizeForm(container, container_height);

    // Drag  / Resize Objects
    var fields_below = $(elements).children(".fields_below");
    var input_position_below = fields_below.children(".input_position_below");

    // $(elements).css({
    // 	// "float":"left",
    // 	"position":"relative",
    // 	"display":"table-cell"

    // });
    var setobj_drag_handle = $('<div class="setObject-drag-handle" style="position:absolute;width: calc(100% + 10px);margin: -5px;height: calc(100% + 10px);"></div>');
    if ($(elements).children(".fields_below").children(".setObject-drag-handle").length == 0 && ($(elements).attr("data-type") != "pickList" && $(elements).find(".form-table").length == 0 && $(elements).find(".form-tabbable-pane").length == 0)) {
        $(elements).children(".fields_below").prepend(setobj_drag_handle)
    } else if ($(elements).children(".fields_below").children(".setObject-drag-handle").length >= 2) {
        $(elements).children(".fields_below").children(".setObject-drag-handle").each(function(eqi) {
            if (eqi == 0) {
                return true;
            }
            $(this).remove();
        })
    } else {
        setobj_drag_handle = false;
    }
    option_focused_component_datas = [];
    $(elements).draggable({
        containment: "parent",
        start: function(event, ui) {
            // if ($(ui.helper).css("float") == "left") {
            //     offset_left = ui.offset.left - ($(".formbuilder_ws").offset().left);
            //     offset_top = ui.offset.top - ($(".formbuilder_ws").position().top);
            //     if (parseInt($(ui.helper).css("top").split("px").join("")) >= 1) {
            //         offset_top = offset_top - parseInt($(ui.helper).css("top").split("px").join(""));
            //     }
            //     if (parseInt($(ui.helper).css("left").split("px").join("")) >= 1) {
            //         offset_left = offset_left - parseInt($(ui.helper).css("left").split("px").join(""));
            //     }
            //     //alert(ui.offset.top+" - "+($(".formbuilder_ws").position().top))
            //     //ETO UNG BEST SOLUTION KO SA NAG KAKAROON NG ADDITIONAL OFFSET
            //     //alert(ui.offset.top+"  -"+($(".formbuilder_ws").offset().top)+" -"+$(window).scrollTop()) // pangdebug ko sa additional offset
            //     //nagkakaroon ng additional offset kasi naka position relative ung mother ng parent ng drag ele
            //     // if( (ui.offset.left - ($(".formbuilder_ws").offset().left)) >= 2 ){
            //     // 	offset_left = offset_left - $(window).scrollLeft();
            //     // }
            //     // if( (ui.offset.top - ($(".formbuilder_ws").offset().top)) >=2 ){
            //     // 	offset_top = offset_top - $(window).scrollTop();
            //     // }

            //     $(ui.helper).draggable("option", "firstFloatLeftOffs", {
            //         "left": offset_left,
            //         "top": offset_top
            //     });

            //     $(ui.helper).css({
            //         "float": "none",
            //         "top": (offset_top) + "px",
            //         "left": (offset_left) + "px",
            //         "position": "absolute"

            //     });
            // }

            $(".component-primary-focus").removeClass("component-primary-focus");
            $(this).addClass("component-primary-focus");
            $(this).addClass("component-ancillary-focus");
        },
        stop: function(event, ui) {
            var drag_ele_origin_pos_left = ui.originalPosition.left;
            var drag_ele_origin_pos_top = ui.originalPosition.top;
            drag_ele_origin_distance_to_current_left = parseInt($(ui.helper).css("left").substring(0, $(ui.helper).css("left").length - 2)) - drag_ele_origin_pos_left;
            drag_ele_origin_distance_to_current_top = parseInt($(ui.helper).css("top").substring(0, $(ui.helper).css("top").length - 2)) - drag_ele_origin_pos_top;
            for (var i in option_focused_component_datas) {
                pos_left = option_focused_component_datas[i]['originLeft'] + drag_ele_origin_distance_to_current_left;
                pos_top = option_focused_component_datas[i]['originTop'] + drag_ele_origin_distance_to_current_top;
                option_focused_component_datas[i]['object'].css({
                    left: pos_left,
                    top: pos_top
                });
                checkCollisionDroppableBoundaries(option_focused_component_datas[i]['object']);
            }
            option_focused_component_datas = [];




            if ($(ui.helper).draggable("option", "firstFloatLeftOffs")) {
                this_ele_data = $(ui.helper).data();
                delete this_ele_data.uiDraggable.options.firstFloatLeftOffs
                $(ui.helper).data(this_ele_data);
            }
            removeRuler(); // Remove Rule after drag stop
            $(container).resizable("option", "minWidth", checkFormMinWidth());
            $(container).resizable("option", "minHeight", checkFormMinHeight());
            checkParentResizableMinWidth($(this));
            checkParentResizableMinHeight($(this));
            $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)));
            $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)));
            $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px");
            $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px");
        },
        drag: function(event, ui) {
            var drag_ele_origin_pos_left = ui.originalPosition.left;
            var drag_ele_origin_pos_top = ui.originalPosition.top;
            drag_ele_origin_distance_to_current_left = parseInt($(ui.helper).css("left").substring(0, $(ui.helper).css("left").length - 2)) - drag_ele_origin_pos_left;
            drag_ele_origin_distance_to_current_top = parseInt($(ui.helper).css("top").substring(0, $(ui.helper).css("top").length - 2)) - drag_ele_origin_pos_top;

            if (option_focused_component_datas.length == 0) {
                if ($(this).hasClass("component-ancillary-focus")) {
                    $(".component-ancillary-focus").each(function(i) {
                        option_focused_component_datas.push({
                            "object": $(this),
                            "originLeft": parseInt($(this).css("left").substring(0, $(this).css("left").length - 2)),
                            "originTop": parseInt($(this).css("top").substring(0, $(this).css("top").length - 2))
                        });
                    })
                } else {
                    option_focused_component_datas.push({
                        "object": $(this),
                        "originLeft": parseInt($(this).css("left").substring(0, $(this).css("left").length - 2)),
                        "originTop": parseInt($(this).css("top").substring(0, $(this).css("top").length - 2))
                    });
                }
            }
            for (var i in option_focused_component_datas) {
                pos_left = option_focused_component_datas[i]['originLeft'] + drag_ele_origin_distance_to_current_left;
                pos_top = option_focused_component_datas[i]['originTop'] + drag_ele_origin_distance_to_current_top;
                option_focused_component_datas[i]['object'].css({
                    left: pos_left,
                    top: pos_top
                });
                checkCollisionDroppableBoundaries(option_focused_component_datas[i]['object']);
            }





            if ($(ui.helper).draggable("option", "firstFloatLeftOffs")) {
                ui.position.left = ui.position.left + $(ui.helper).draggable("option", "firstFloatLeftOffs").left;
                ui.position.top = ui.position.top + $(ui.helper).draggable("option", "firstFloatLeftOffs").top;
            }
            //$(".object_properties").popover('hide')

            $(this).css({
                "float": "none",
                "top": (ui.position.top) + "px",
                "left": (ui.position.left) + "px",
                "position": "absolute"

            });
            // Show Ruler guide                   
            var drag_ele_current_pos_left = ui.offset.left
            var drag_ele_current_pos_top = ui.offset.top

            dragShowVerticalRuler($(ui.helper), drag_ele_current_pos_left, drag_ele_current_pos_top, container);
            dragShowHorizontalRuler($(ui.helper), drag_ele_current_pos_left, drag_ele_current_pos_top, container);
        },
        snapMode: "outer",
        snap: ".setObject, .form-builder-ruler",
        snapTolerance: "5",
        handle: setobj_drag_handle
    }).on({
        "mousedown": function(event) {
            event.stopPropagation();
            if (event.altKey) {
                $(this).draggable("option", "containment", $(".workspace.formbuilder_ws"));
            } else {
                $(this).draggable("option", "containment", "parent");
            }

            var eto_event = event;
            var eto_dis = $(this);
            if (eto_event.ctrlKey) {
                if (eto_dis.hasClass("component-ancillary-focus")) {
                    if (eto_dis.hasClass("component-primary-focus")) {
                        eto_dis.removeClass("component-primary-focus");
                        eto_dis.removeClass("component-ancillary-focus");
                        $(".component-ancillary-focus").last().addClass("component-primary-focus");
                    } else {
                        $(".component-primary-focus").removeClass("component-primary-focus");
                        eto_dis.addClass("component-primary-focus");
                    }
                } else {
                    eto_dis.addClass("component-ancillary-focus");

                    $(".component-primary-focus").removeClass("component-primary-focus");
                    eto_dis.addClass("component-primary-focus");
                }
            } else if (!eto_dis.hasClass("component-ancillary-focus") && !eto_dis.hasClass("component-primary-focus")) {
                $(".component-ancillary-focus").removeClass("component-ancillary-focus");
                eto_dis.addClass("component-ancillary-focus");

                $(".component-primary-focus").removeClass("component-primary-focus");
                eto_dis.addClass("component-primary-focus");
            } else {
                if (eto_dis.hasClass("component-ancillary-focus")) {
                    if (eto_dis.hasClass("component-primary-focus")) {
                        // eto_dis.removeClass("component-primary-focus");
                        // eto_dis.removeClass("component-ancillary-focus");
                        // $(".component-ancillary-focus").last().addClass("component-primary-focus");
                    } else {
                        $(".component-primary-focus").removeClass("component-primary-focus");
                        eto_dis.addClass("component-primary-focus");
                    }
                } else {
                    eto_dis.addClass("component-ancillary-focus");

                    $(".component-primary-focus").removeClass("component-primary-focus");
                    eto_dis.addClass("component-primary-focus");
                }
            }
        },
        "dblclick": function(e) {
            e.stopPropagation();
            $(this).find(".object_setup.object_properties").eq(0).click();
        }
    })
    //parseInt($(elements).find(".getFields")) + parseInt($(elements).find(".getFields").css("padding-left").split("px").join(""))

    //RESIZABLE KINDS OF FIELDS
    var fieldCounterID = $(elements).attr("data-object-id");
    var gettingFields = $(elements).find(".getFields_" + fieldCounterID).eq(0);
    if (gettingFields.prop("tagName") == "TEXTAREA") {
        $(elements).resizable({
            containment: "parent",
            handles: 's,e,se',
            autoHide: true,
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                // ui.size.width = ui.size.width - 10;
                // ui.size.height = ui.size.height - 10;
                console.log(ui.size.width)
                var dis_id = $(this).attr("data-object-id");
                var obj_fld_container = $(this).find("#obj_fields_" + dis_id);
                var obj_fld_container_pos_top = obj_fld_container.position().top;
                obj_fld_container.css({
                    "height": "calc(100% - " + (obj_fld_container_pos_top) + "px)"
                });
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else if (gettingFields.prop("tagName") == "IMG") {
        $(elements).find(".uiform-image-resizable").resizable({
            // containment: "parent",
            handles: 'n,s,e,w,se',
            start: function(event, ui) {
                // console.log($(this))
            },
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                ui.size.width = ui.size.width - 10;
                ui.size.height = ui.size.height - 10;
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else if (gettingFields.attr("type") == "radio" || gettingFields.attr("type") == "checkbox") {
        //walang resizable itong si checkbox at si radio
	} else if (gettingFields.parents(".uiform-image-resizable").find(".ImagegetFields_" + fieldCounterID).length >= 1) {
		$(elements).find(".uiform-image-resizable").resizable({
            // containment: "parent",
            handles: 'n,s,e,w,se',
            start: function(event, ui) {
                // console.log($(this))
            },
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                ui.size.width = ui.size.width - 10;
                ui.size.height = ui.size.height - 10;
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else if (elements.find("table.form-table").length >= 1) {
        $(elements).resizable({
            containment: "parent",
            handles: 's',
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                // ui.size.width = ui.size.width - 10;
                // ui.size.height = ui.size.height - 10;
                // console.log(ui.size.width)
                var dis_id = $(this).attr("data-object-id");
                var obj_fld_container = $(this).find("#obj_fields_" + dis_id);
                var obj_fld_container_pos_top = obj_fld_container.position().top;
                obj_fld_container.css({
                    "height": "calc(100% - " + (obj_fld_container_pos_top) + "px)"
                });
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else if (elements.find(".form-tabbable-pane").length >= 1) {
        $(elements).resizable({
            containment: "parent",
            handles: 'e',
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                ui.size.width = ui.size.width - 10;
                ui.size.height = ui.size.height - 10;
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else if (gettingFields.attr("type") == "text") {
        $(elements).resizable({
            containment: "parent",
            handles: 's,e',
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                ui.size.width = ui.size.width - 10;
                ui.size.height = ui.size.height - 10;
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else if (elements.attr("data-type") == "createLine") {
        $(elements).resizable({
            containment: "parent",
            handles: 'e',
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                ui.size.width = ui.size.width - 10;
                ui.size.height = ui.size.height - 10;
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    } else {
        $(elements).resizable({
            containment: "parent",
            handles: 'n,s,e,w',
            resize: function(event, ui) {
                //$(".object_properties").popover('hide');
                ui.size.width = ui.size.width - 10;
                ui.size.height = ui.size.height - 10;
            },
            stop: function(ee, ui) {
                // $(container).resizable("option", "minWidth", checkFormMinWidth());
                // $(container).resizable("option", "minHeight", checkFormMinHeight());
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minHeight", checkParentResizableMinHeight($(this)))
                $(this).parents(".ui-resizable").eq(0).resizable("option", "minWidth", checkParentResizableMinWidth($(this)))
                $(this).parents(".ui-resizable").eq(0).css("min-height", (checkParentResizableMinHeight($(this))) + "px")
                $(this).parents(".ui-resizable").eq(0).css("min-width", (checkParentResizableMinWidth($(this))) + "px")
            }
        });
    }
    if ($(elements).data()) {
        if ($(elements).data().uiResizable) {
            $(elements).resizable("option", "minWidth", 20);
        }
    }
    // Hide / Show Properties of objects
    prop_hovering();

    // Click Object Properties
    //$(".object_properties").popover({
    //    html : true, 
    //    content: function() {
    //	var properties_type = $(this).attr("data-properties-type");
    //	return  object_properties(properties_type);
    //    },
    //    container: "body"
    //});

















    $('#object_properties_' + properties_id).on({'click': function(e) { //ETO UNG CLICK NG PROPERTIES

            // Remove other open popover
            //$('.object_properties').not(this).popover('hide');
            var properties_type = $(this).attr("data-properties-type");
            var object_id = $(this).attr("data-object-id");
            var data_type = $("#setObject_" + object_id).attr("data-type");
            var data_object_type = $(this).attr("data-object-type");
            //data-object-type
            // Show properties on the modal box
            jDialog(object_properties(properties_type, data_type, data_object_type), "", "800", "", "", function() {
            });


            $("#popup_container").attr("data-object-id", object_id);


            //WHEN table-name is existing
            if($("#popup_content").find('[name="set-prop-table-name"]').length >= 1 ){
                var DOI = $("#popup_container").attr("data-object-id");
                var the_element = $("#setObject_"+DOI);
                if(the_element.find(".form-table").length >= 1){
                    $("#popup_content").find('[name="set-prop-table-name"]').on({
                        "keyup":function(e){
                            var dis_value = $(this).val();
                            var DOI = $("#popup_container").attr("data-object-id");
                            var the_element = $("#setObject_"+DOI);

                            the_element.find(".form-table").eq(0).attr("table-name",dis_value);
                        }
                    })
                    if(the_element.find(".form-table").eq(0).attr("table-name") ){
                        $("#popup_content").find('[name="set-prop-table-name"]').val(the_element.find(".form-table").eq(0).attr("table-name") )
                    }
                }
            }

            //WHEN data-properties-type="lblAllowLabel-RC"
            if($('[data-properties-type="lblAllowLabel-RC"]').length >= 1){
                $('[data-properties-type="lblAllowLabel-RC"]').on("change",function(){
                    var choose_value = $(this).val();
                    var DOI = $("#popup_container").attr("data-object-id");
                    var the_element = $("#setObject_"+DOI);

                    if(choose_value == "Yes"){
                        if(the_element.attr("data-type") == "checkbox"){
                            $("#setObject_"+DOI).find(".checkbox-input-label").show();
                        }else{
                            $("#setObject_"+DOI).find(".radio-input-label").show();
                        }
                    }else{
                        if(the_element.attr("data-type") == "checkbox"){
                            $("#setObject_"+DOI).find(".checkbox-input-label").hide();
                        }else{
                            $("#setObject_"+DOI).find(".radio-input-label").hide();
                        }
                    }
                });

            }

            //WHEN PICKLIST SELECTION IS EXISTING
            if ($("[name='selection_type']").length >= 2) {
                var DOI = $("#popup_container").attr("data-object-id");
                if ($("#setObject_" + DOI).find("[picklist-button-id='picklist_button_" + DOI + "']").attr("selection-type")) {
                    $("[name='selection_type'][value='" + $("#setObject_" + DOI).find("[picklist-button-id='picklist_button_" + DOI + "']").attr("selection-type") + "']").prop("checked", true);
                }
                $("[name='selection_type']").on("change", function() {
                    var dis_value = $(this).val();
                    var DOI = $("#popup_container").attr("data-object-id");
                    $("#setObject_" + DOI).find("[picklist-button-id='picklist_button_" + DOI + "']").attr("selection-type", dis_value);
                });
            }


            //WHEN VISIBILITY IS EXISTING
            if ($(".chk_Visibility").length >= 1) {
                $(".chk_Visibility").find("[name='visibility-choices']").on("change.field_visibility", function(e) {
                    var DOI = $("#popup_container").attr("data-object-id");
                    if ($(this).val() == "computed") {
                        // alert( $(".chk_Visibility").find(".visibility-computed").val() )
                        $(".getFields_" + DOI).attr("visible-formula", $(".chk_Visibility").find(".visibility-computed").val());
                        $(".getFields_" + DOI).attr("field-visible", "computed");
                    } else if ($(this).val() == "no") {
                        $(".getFields_" + DOI).attr("field-visible", false);
                    } else {
                        $(".getFields_" + DOI).attr("field-visible", true);
                    }
                });
                //visibility formula
                $(".chk_Visibility").find(".visibility-formula").on("keyup", function() {
                    var DOI = $("#popup_container").attr("data-object-id");
                    $(".getFields_" + DOI).attr("visible-formula", $(this).val());
                });

                //RESTORING VALUES
                if (typeof $(".getFields_" + object_id).attr("field-visible") != "undefined") {
                    $(".chk_Visibility").find("[name='visibility-choices'][value='" + $(".getFields_" + object_id).attr("field-visible") + "']").prop("checked", true);
                    if ($(".getFields_" + object_id).attr("field-visible") == "computed") {
                        $(".chk_Visibility").find(".visibility-formula").val($(".getFields_" + object_id).attr("visible-formula"));
                    }
                }
            }

            //WHEN CHECKBOX EVENT TRIGGER
            if ($("#refreshtrigger").length >= 1) {
                //bind onchange of refresh trigger properties
                $("#refreshtrigger").on({
                    "change": function() {
                        var DOI = $("#popup_container").attr("data-object-id");
                        $(".getFields_" + DOI).attr("lookup-event-trigger", $(this).prop("checked"));
                    }
                });
                //restore value of properties
                if (typeof $(".getFields_" + object_id).attr("lookup-event-trigger") != "undefined") {
                    if ($(".getFields_" + object_id).attr("lookup-event-trigger") == "false") {
                        $("#refreshtrigger").prop("checked", false);
                    } else {
                        $("#refreshtrigger").prop("checked", true);
                    }
                }
            }

            //WHEN FORMTABLE PROPERTY IS EXISTING FOR DYNAMIC TABLE
            if ($(".form_table_type").length >= 1) {
                var form_table_type_ele = $(".form_table_type");
                //RESTORING THE SELECTED VALUE
                if ($("#setObject_" + object_id).find(".form-table").eq(0).attr("repeater-table") == "true") {
                    form_table_type_ele.children(".form-table-type").children("option[value='dynamic']").prop("selected", true);
                }
                //SETTINGS OF TABLE TYPE WHEN ON CHANGE
                form_table_type_ele.children(".form-table-type").on({
                    "change": function() {
                        var DOI = $("#popup_container").attr("data-object-id");
                        if ($(this).val() == "normal") {
                            $("#setObject_" + DOI).find(".form-table").eq(0).closest(".table-wrapper").find(".table-actions-ra.action-row-add").show();
                            $("#setObject_" + DOI).find(".form-table").eq(0).removeAttr("repeater-table");
                        } else if ($(this).val() == "dynamic") {
                            var rows_length = $("#setObject_" + DOI).find(".form-table").eq(0).children("tbody").children("tr").length;
                            if (rows_length == 1) {
                                $("#setObject_" + DOI).find(".form-table").eq(0).closest(".table-wrapper").find(".table-actions-ra.action-row-add").hide();
                                $("#setObject_" + DOI).find(".form-table").eq(0).attr("repeater-table", true);
                            } else {
                                var self = $(this);
                                var conf = "Selecting dynamic row, will delete the existing rows below\nAnd only the first row will be left.\nWould you still like to continue?\nNOTE: you cannot undone deleted rows.";
                                jConfirm(conf, 'Confirmation Dialog', '', '', '', function(answer) {
                                    if (answer == true) {
                                        $("#setObject_" + DOI).find(".form-table").eq(0).children("tbody").children("tr").each(function(eqi) {
                                            if (eqi >= 1) {
                                                $(this).remove();
                                            }
                                        });
                                        $("#setObject_" + DOI).find(".form-table").eq(0).closest(".table-wrapper").find(".table-actions-ra.action-row-add").hide();
                                        $("#setObject_" + DOI).find(".form-table").eq(0).attr("repeater-table", true);
                                    } else {
                                        self.val("normal");
                                    }
                                });
                            }
                        }
                    }
                });
            }

            //WHEN EMBED PROPERTY IS EXISTING
            if ($(".embedProperty").length >= 2) {
                var prop_choice_embed_ele = $('[name="embed_rfc_choice"]');
                if(prop_choice_embed_ele.length >= 1){
                    prop_choice_embed_ele.on("change",function(e){
                        var DOI = $("#popup_container").attr("data-object-id");
                        var value_embed = $(this).val();
                        if(value_embed == "static"){
                            $(".embed-result-field-computed-c").css("display","none");
                            $(".embed-result-field-c").css("display","");
                        }else if(value_embed == "computed"){
                            $(".embed-result-field-c").css("display","none");
                            $(".embed-result-field-computed-c").css("display","");
                        }
                        $("#setObject_" + DOI).find(".getFields_"+ DOI).attr('rfc-choice',value_embed);
                    });
                }
                var DOI = $("#popup_container").attr("data-object-id");

                if($("#setObject_" + DOI).find(".getFields_"+ DOI).attr('rfc-choice') ){
                    // alert($("#setObject_" + DOI).find(".getFields_"+ DOI).attr('sc-choice') );
                    var embed_choice_value = $("#setObject_" + DOI).find(".getFields_"+ DOI).attr('rfc-choice');
                    if(embed_choice_value == "computed"){
                        // $("[value='computed']",prop_choice_embed_ele).prop("checked",true);
                        $('[value="computed"]'+prop_choice_embed_ele.selector).click();
                        $(".embed-result-field-c").css("display","none");
                    }else{
                        // $("[value='static']",prop_choice_embed_ele).prop("checked",true);
                        $('[value="static"]'+prop_choice_embed_ele.selector).click();
                        $(".embed-result-field-computed-c").css("display","none");
                    }
                }
                if($(".embed-result-field-formula").length >= 1 ){
                    $(".embed-result-field-formula").on("keyup",function(){
                        var DOI = $("#popup_container").attr("data-object-id");
                        $("#setObject_" + DOI).find(".getFields_"+ DOI).attr('embed-computed-formula',$(this).val());
                    });
                    if($("#setObject_" + DOI).find(".getFields_"+ DOI).attr('embed-computed-formula') ){
                        $(".embed-result-field-formula").val(
                            $("#setObject_" + DOI).find(".getFields_"+ DOI).attr('embed-computed-formula')
                        );
                    }
                }

                var embed_source_form_ele_container = $(".embedProperty").find(".embed_source_form");
                var loading_content = $('<div class="getFromsLoader form-select" style="display:inline-block;position:relative;vertical-align:middle;text-align:center;"><label style="color:black;position:reltive;font-size: 15px;display:inline-block;">Loading...</label><img src="/images/loader/loader.gif" class="display processorLoad" style="display: inline-block;"/></div>');

                //EMBED GET FORM LIST
                embed_source_form_ele_container.children(".embed-source-form").hide();
                embed_source_form_ele_container.prepend(loading_content);
                var embed_source_lookup_field_ele_container = $(".embedProperty").find(".embed_source_lookup_field");
                if (embed_source_lookup_field_ele_container.find(".getFromsLoader").length == 0) {
                    var loading_content_active_fields = $('<div class="getFromsLoader form-select" style="display:inline-block;position:relative;vertical-align:middle;text-align:center;"><label style="color:black;position:reltive;font-size: 15px;display:inline-block;">Loading...</label><img src="/images/loader/loader.gif" class="display processorLoad" style="display: inline-block;"/></div>');
                    embed_source_lookup_field_ele_container.find(".embed-source-lookup-field").hide();
                    embed_source_lookup_field_ele_container.after(loading_content_active_fields);
                }
                $.post("/ajax/formbuilder", {action: "getFormList"}, function(dataEchoResults) {
                    var json_p = JSON.parse(dataEchoResults);
                    var embed_source_form_ele_container = $(".embedProperty").find(".embed_source_form");
                    //GET LIST OF FORMS
                    var collect_append_option = '<option>--Select--</option>';
                    for (var c in json_p) {
                        console.log(json_p[c])
                        collect_append_option
                                += '<option frm-id="' + json_p[c]["wsID"] + '" active-fields="' + json_p[c]["active_fields"] + '" value="' + json_p[c]["wsID"] + '" >' + json_p[c]["form_name"] + '</option>';
                    }

                    loading_content.fadeOut(function() {
                        var embed_source_form_ele_container = $(".embedProperty").find(".embed_source_form");

                        embed_source_form_ele_container.children(".embed-source-form").html(collect_append_option);
                        embed_source_form_ele_container.children(".embed-source-form").show();
                        loading_content_active_fields.fadeOut(function() {
                            embed_source_lookup_field_ele_container.find(".embed-source-lookup-field").show();
                            $(this).remove();
                        });

                        //RESTORE SAVED VALUES
                        var field_id_on_form = $("#popup_container").attr("data-object-id");
                        if (typeof $(".getFields_" + field_id_on_form).attr("embed-source-form-val-id") != "undefined") {
                            embed_source_form_ele_container.children(".embed-source-form").children("option[frm-id='" + $(".getFields_" + field_id_on_form).attr("embed-source-form-val-id") + "']").prop("selected", true);
                        }

                        //GET FORM ACTIVE FIELD LIST BASED ON SELECTED SOURCE LIST OF FORMS
                        var collect_append_option_active_field = "<option>--Select--</option><option value='TrackNo' >TrackNo</option>";
                        if (embed_source_form_ele_container.children(".embed-source-form").children("option:selected").length >= 1) {
                            var active_fields = embed_source_form_ele_container.children(".embed-source-form").children("option:selected").attr("active-fields");
                            if (typeof active_fields != "undefined") {
                                if (active_fields.length >= 1) {
                                    active_fields = active_fields.split(",");
                                    for (var ctr = 0; ctr < active_fields.length; ctr++) {
                                        collect_append_option_active_field += '<option value="' + active_fields[ctr] + '">' + active_fields[ctr] + '</option>';
                                    }
                                }
                            }
                        }
                        var appended_options_active_field = $(collect_append_option_active_field);
                        embed_source_lookup_field_ele_container.find(".embed-source-lookup-field").html(appended_options_active_field);
                        //RESTORING VALUE OF SELECTED ACTIVE FIELD OF SOURCE FORM
                        var getFieldSourceFormID_val = $(".getFields_" + field_id_on_form).attr("embed-source-form-val-id");
                        var getFieldSourceFormLookupField_val = $(".getFields_" + field_id_on_form).attr("embed-source-lookup-active-field-val");
                        if (typeof getFieldSourceFormLookupField_val != "undefined") {
                            if (
                                    getFieldSourceFormID_val == embed_source_form_ele_container.children(".embed-source-form").children("option:selected").val() &&
                                    appended_options_active_field.parent().children("option[value='" + getFieldSourceFormLookupField_val + "']").length >= 1
                                    ) {
                                appended_options_active_field.parent().children("option[value='" + getFieldSourceFormLookupField_val + "']").prop("selected", true);
                            }
                        }

                        //SET ONCHANGE EVENT EMBED SOURCE FORMS
                        embed_source_form_ele_container.children(".embed-source-form").on({
                            "change": function() {
                                var embed_source_form_ele_container = $(".embedProperty").find(".embed_source_form");

                                var field_id_on_form = $("#popup_container").attr("data-object-id");
                                $(".getFields_" + field_id_on_form).attr("embed-source-form-val-id", $(this).val());

                                //GET ACTIVE FIELDS OF SOURCE FORM
                                var collect_append_option_active_field = "<option>--Select--</option>";
                                if (embed_source_form_ele_container.children(".embed-source-form").children("option:selected").length >= 1) {
                                    var active_fields = embed_source_form_ele_container.children(".embed-source-form").children("option:selected").attr("active-fields");
                                    if (typeof active_fields != "undefined") {
                                        if (active_fields.length >= 1) {
                                            active_fields = active_fields.split(",");
                                            for (var ctr = 0; ctr < active_fields.length; ctr++) {
                                                collect_append_option_active_field += '<option value="' + active_fields[ctr] + '">' + active_fields[ctr] + '</option>';
                                            }
                                        }
                                    }
                                }
                                var appended_options_active_field = $(collect_append_option_active_field);
                                embed_source_lookup_field_ele_container.find(".embed-source-lookup-field").html(appended_options_active_field);

                                //RESTORING VALUE OF SELECTED ACTIVE FIELD OF SOURCE FORM
                                var getFieldSourceFormID_val = $(".getFields_" + field_id_on_form).attr("embed-source-form-val-id");
                                var getFieldSourceFormLookupField_val = $(".getFields_" + field_id_on_form).attr("embed-source-lookup-active-field-val");
                                if (typeof getFieldSourceFormLookupField_val != "undefined") {
                                    if (
                                            getFieldSourceFormID_val == $(this).val() &&
                                            appended_options_active_field.parent().children("option[value='" + getFieldSourceFormLookupField_val + "']").length >= 1
                                            ) {
                                        // alert("HALA")
                                        // console.log(appended_options_active_field)
                                        // console.log("kulangot")
                                        // console.log(getFieldSourceFormLookupField_val)
                                        // console.log($(appended_options_active_field,"[value='"+getFieldSourceFormLookupField_val+"']"))
                                        appended_options_active_field.parent().children("option[value='" + getFieldSourceFormLookupField_val + "']").prop("selected", true);
                                    }
                                }


                            }
                        })
                        $(this).remove();
                    });
                });



                //EMBED GET FORM SOURCE LOOKUP ACTIVE FIELDS 
                var embed_source_lookup_field_ele_container = $(".embedProperty").find(".embed_source_lookup_field");
                embed_source_lookup_field_ele_container.find(".embed-source-lookup-field").html('<option>--Select--</option>');

                //SET ON CHANGE OF embed source lookup active field
                embed_source_lookup_field_ele_container.find(".embed-source-lookup-field").on({
                    "change": function() {
                        $(".getFields_" + field_id_on_form).attr("embed-source-lookup-active-field-val", $(this).val());
                    }
                });




                //EMBED GET LIST OF FIELD NAMES
                var embed_result_field_ele_container = $(".embedProperty").find(".embed_result_field");
                //COLLECT FIELD NAMES
                // alert("TESTING")

                var field_names = '<option>--Select--</option>';
                $(".workspace.formbuilder_ws").find(".setObject").each(function() {
                    // console.log("WHOA")
                    // console.log($(this).find(".getFields").eq(0))
                    if (
                            $(this).find(".form-table").length >= 1 ||
                            $(this).find(".form-tabbable-pane").length >= 1 ||
                            $(this).find('[data-type="createLine"]').length >= 1 ||
                            $(this).attr("data-type") == "labelOnly" ||
                            $(this).attr("data-type") == "embeded-view" ||
                            $(this).attr("data-type") == "imageOnly"
                            ) {
                        return true;
                    }
                    var obj_id = $(this).attr("data-object-id");
                    var obj_fields = $(this).find(".getFields_" + obj_id).eq(0);
                    if (typeof obj_fields == "undefined") {

                    } else {
                        field_names
                                += '<option obj-id="' + obj_id + '" value="' + obj_fields.attr("name") + '">' + obj_fields.attr("name") + '</option>';
                    }
                });
                embed_result_field_ele_container.find(".embed-result-field").html(field_names);

                //RESTORE SAVED VALUES
                var field_id_on_form = $("#popup_container").attr("data-object-id");
                if (typeof $(".getFields_" + field_id_on_form).attr("erf-obj-id-val") != "undefined") {
                    embed_result_field_ele_container.find(".embed-result-field").find("option[obj-id='" + $(".getFields_" + field_id_on_form).attr("erf-obj-id-val") + "']").prop("selected", true);
                }

                //SET ONCHANGE EVENT
                // console.log(embed_result_field_ele_container)
                embed_result_field_ele_container.find(".embed-result-field").on({
                    "change": function() {
                        var selected_obj_id = $(this).children("option:selected").attr("obj-id");
                        var field_id_on_form = $("#popup_container").attr("data-object-id");
                        $(".getFields_" + field_id_on_form).attr("embed-result-field-val", $(this).val());
                        $(".getFields_" + field_id_on_form).attr("erf-obj-id-val", selected_obj_id);
                    }
                });
            }

            //WHEN ALIGNMENT OF RADIO AND CHECKBOX IS EXISTING
            if ($(".rcAlignmentProperty").length >= 1) {
                var property_container = $(".rcAlignmentProperty");
                var DOI = $("#popup_container").attr("data-object-id");

                //RESTORE VALUES
                if ($("#setObject_" + DOI).find(".rc-prop-alignment").hasClass("rc-align-vertical")) {
                    property_container.find(".rc-alignment").val("vertical");
                } else if ($("#setObject_" + DOI).find(".rc-prop-alignment").hasClass("rc-align-horizontal")) {
                    property_container.find(".rc-alignment").val("horizontal");
                }

                //SET ONCHANGE OF THE PROPERTY
                property_container.find(".rc-alignment").on({
                    "change": function() {
                        var this_value = $(this).val();
                        var DOI = $("#popup_container").attr("data-object-id");
                        if (this_value == "vertical") {
                            $("#setObject_" + DOI).attr("rc-align-type", "vertical");
                            $("#setObject_" + DOI).find(".rc-prop-alignment").removeClass("rc-align-horizontal").addClass("rc-align-vertical");
                        } else if (this_value == "horizontal") {
                            $("#setObject_" + DOI).attr("rc-align-type", "horizontal");
                            $("#setObject_" + DOI).find(".rc-prop-alignment").removeClass("rc-align-vertical").addClass("rc-align-horizontal");
                        }
                    }
                })
            }

            //WHEN obj_inputValidation IS EXISTING
            if ($(".obj_inputValidation").length >= 1) {
                var obj_prop_data_validation = $(".obj_inputValidation").children(".field-formula-validation").eq(0);
                //restoring value of the specific field for validation
                if ($('.getFields_' + object_id + '[field-formula-validation]').length >= 1) {
                    obj_prop_data_validation.val($('.getFields_' + object_id + '[field-formula-validation]').attr("field-formula-validation"));
                }

                obj_prop_data_validation.on({
                    "keyup": function(e) {
                        //saving value to attribute of a specific field
                        this_value = $(this).val();
                        $(".getFields_" + object_id).attr("field-formula-validation", this_value);

                        var json_data_valid = $("body").data();
                        //saving to json
                        if (typeof json_data_valid[object_id] != "undefined") {
                            json_data_valid[object_id].field_formula_validation = "" + this_value;
                        } else {
                            json_data_valid[object_id] = {
                                field_formula_validation: this_value
                            };
                        }
                        $("body").data(json_data_valid);
                    }
                });
            }
            //WHEN obj_inputValidationMessage IS EXISTING
            if ($(".obj_inputValidationMessage").length >= 1) {
                var obj_prop_data_validation = $(".obj_inputValidationMessage").children(".field-formula-validation-message").eq(0);
                //restoring value of the specific field for validation
                if ($('.getFields_' + object_id + '[field-formula-validation-message]').length >= 1) {
                    obj_prop_data_validation.val($('.getFields_' + object_id + '[field-formula-validation-message]').attr("field-formula-validation-message").replace(/<[\s]*?br[\s]*?[\/]?[\s]*?>/g, "\n"));
                }

                obj_prop_data_validation.on("keyup", function() {
                    this_value = $(this).val().replace(/\n/g, "<br/>");
                    $(".getFields_" + object_id).attr("field-formula-validation-message", this_value);

                    var json_data_valid_message = $("body").data();
                    //saving to json
                    if (typeof json_data_valid_message[object_id] != "undefined") {
                        json_data_valid_message[object_id].field_formula_validation = "" + this_value;
                    } else {
                        json_data_valid_message[object_id] = {
                            field_formula_validation_message: this_value
                        };
                    }
                    $("body").data(json_data_valid_message);
                });
            }

            defaultValuesFN(object_id);
            // Show Scroll bar of popover
            // $('.scrollbarM').perfectScrollbar({
            // 				wheelSpeed: 20,
            // 				wheelPropagation: false
            // 			      });
            $(".ps-scrollbar-x").hide();

            // Get Object Attribute
            var object_type = $(this).attr("data-object-type");
            var object_id = $(this).attr("data-object-id");

            //setObject_1
            $(".obj_prop").attr("data-object-id", object_id);
            $(".obj_prop").attr("id", "obj_prop" + object_id);

            // Get Field Height
            var field_height = $("#getFields_" + object_id).height();
            var field_width = $("#getFields_" + object_id).width();

            $("#obj_prop" + object_id + "[data-properties-type='lblFieldHeight']").val(field_height);
            $("#obj_prop" + object_id + "[data-properties-type='lblFieldWidth']").val(field_width);

            // Get Value of the Object Properties On Text Field
            $(".obj_prop").each(function() {
                var json = $("body").data();
                var objID = $(this).attr("data-object-id");
                var data_properties_type = $(this).attr("data-properties-type");
                if (json['' + objID + '']) {
                    var objID = $(this).attr("data-object-id");
                    var valueOnJSON = json['' + objID + '']['' + data_properties_type + ''];
                    if ($('[data-properties-type="defaultValueType"]').length >= 1) {
                        if (json['' + objID + '']["defaultValueType"]) {
                            $('[data-properties-type="defaultValueType"][value="' + json['' + objID + '']["defaultValueType"] + '"]').prop('checked', true);
                        }
                    }
                    if ($('[data-properties-type="defaultValue"]').length >= 1) {
                        if (json['' + objID + '']["defaultValue"]) {
                            $('[data-properties-type="defaultValue"][value="' + json['' + objID + '']["defaultValue"] + '"]').prop('checked', true);
                        }
                    }
                    if (data_properties_type == "lblFieldType") {
                        $(this).children("option[data-input-type='" + $("#getFields_" + objID).attr("data-input-type") + "']").prop("selected", true);
                    } else if (valueOnJSON) {
                        $(this).val(valueOnJSON);
                    }
                }
            });
            var json = $("body").data();
            var object_id = if_undefinded($(".workflow-processor").attr("data-object-id"), $("#popup_container").attr("data-object-id"));
            if (json['' + object_id + '']) {
                getprocessor(json['' + object_id + '']['processor-type'], json['' + object_id + '']['processor']);
            }

            // Color Picker
            var lblFontColor = $("#lbl_" + object_id).css("color");
            $(".chngColor[data-properties-type='lblFontolor']").spectrum({
                color: lblFontColor,
                change: function(color) {
                    var type = $(this).attr("data-type");
                    $("#lbl_" + object_id).css("color", color.toHexString());
                    var data_properties_type = $(this).attr("data-properties-type");
                    var json = $("body").data();
                    if (json['' + object_id + '']) {
                        var prop_json = json['' + object_id + ''];
                    } else {
                        var prop_json = {};
                    }

                    prop_json['' + data_properties_type + ''] = color.toHexString()
                    json['' + object_id + ''] = prop_json;
                    $("body").data(json);
                }
            });

            // Color Picker
            var lblFieldColor = $(".getFields_" + object_id).css("border-color");
            $(".chngColor[data-properties-type='lblFieldColor']").spectrum({
                color: lblFieldColor,
                change: function(color) {
                    var type = $(this).attr("data-type");

                    $(".getFields_" + object_id).css("border-color", color.toHexString());
                    var data_properties_type = $(this).attr("data-properties-type");
                    var json = $("body").data();
                    if (json['' + object_id + '']) {
                        var prop_json = json['' + object_id + ''];
                    } else {
                        var prop_json = {};
                    }
                    prop_json['' + data_properties_type + ''] = color.toHexString()
                    json['' + object_id + ''] = prop_json;
                    $("body").data(json);
                }
            });
            //scroll
            $('#content-dialog-scroll').perfectScrollbar();
        }});
    numericFunction(".prop_numeric_val");










    $(".object_setup").tooltip({
        html: true,
        placement: "top"
    });
}

function setFormProperties() {
    var json = $("body").data();
    $("body").on("keyup", "#workspace_title", function() {
        json.workspace_title = $(this).val();
    });
    $("body").on("keyup", "#workspace_displayName", function() {
        json.workspace_displayName = $(this).val();
    });
    $("body").on("keyup", "#workspace_prefix", function() {
        json.workspace_prefix = $(this).val();
    });
    $("body").on("change", "#workspace_type", function() {
        json.workspace_type = $(this).val();
    });
    $("body").on("change", "#form_category", function() {
        json.form_category = $(this).val();
    });
}


var picklist = {
    init: function() {
        this.addEventListeners();
    },
    addEventListeners: function() {
        var self = this;

        $('body').on('click', '[data-type="picklist_selection"]', function() {
            var val = $(this).val();

            if (val == 'Forms') {
                $('.form_selection').removeClass('display');
                $('.select_form_picklist').removeClass('display');
                $('.keyword_view').addClass('display');
                $('.keyword_search').addClass('display');


                self.getForms(function(data) {
                    $('.picklist_form_type').html('<option value="0">----------------------------Select----------------------------</option>');
                    for (var index in data) {
                        $('.picklist_form_type').append('<option value="' + data[index].wsID + '" fields="' + data[index].active_fields + '">' + data[index].form_name + '</option>');
                    }

                    $('.display_columns').html('');
                    $('.picklist_form_field').html('<option value="0">----------------------------Select----------------------------</option>');
                });

            } else {
                $('.form_selection').addClass('display');
                $('.keyword_view').removeClass('display');
                $('.keyword_search').removeClass('display');
                $('.select_form_picklist').addClass('display');
            }
        });

        $('body').on('change', '.picklist_form_type', function() {
            var fields = $(this).find('option:selected').attr('fields');

            fields = fields.split(',');
            $('.display_columns').html('');
            $('.picklist_form_field').html('<option value="0">----------------------------Select----------------------------</option>');
            $('.picklist_form_field').append('<option value="TrackNo">TrackNo</option>');
            $('.display_columns').append('<input name="chk_displayColumns" type="checkbox" value="TrackNo">TrackNo</input><br/>');
            for (var ctr = 0; ctr <= fields.length - 1; ctr++) {
                $('.picklist_form_field').append('<option value="' + fields[ctr] + '">' + fields[ctr] + '</option>');
                $('.display_columns').append('<input name="chk_displayColumns" type="checkbox" value="' + fields[ctr] + '">' + fields[ctr] + '</input><br/>');
            }
        });

        $('body').on('click', '.select_form_picklist_multiple', function() {
            var returnFields = $(this).attr('return-field');
            var values = [];

            $('[name="chk_selected_values"]:checked').each(function() {
                values.push($(this).val());
            });

            $('#' + returnFields).val(values.join(';'));
            $('#popup_cancel').click();
        });

        $('body').on('click', '#select_form_picklist', function() {
            var pickListButton = $(this).attr('dialog-button-id');
            var returnField = $(this).attr('return-field');
            var formId = $('.picklist_form_type').val();
            var formName = $('.picklist_form_type option:selected').text();
            var fieldName = $('.picklist_form_field').val();
            var displayColumns = [];

            $('[name="chk_displayColumns"]:checked').each(function() {
                displayColumns.push($(this).val());
            });
            $('[picklist-button-id="' + pickListButton + '"]').attr('picklist-type', 'Forms');
            $('[picklist-button-id="' + pickListButton + '"]').attr('form-id', formId);
            $('[picklist-button-id="' + pickListButton + '"]').attr('return-field-name', fieldName);
            $('[picklist-button-id="' + pickListButton + '"]').attr('formname', formName);
            $('[picklist-button-id="' + pickListButton + '"]').attr('display_columns', displayColumns.join());
            $('#' + returnField).attr('placeholder', 'Please select ' + formName);
            $('#popup_cancel').click();
        });

        $('body').on('click', '.pickListButton', function() {
            ui.block();
            var picklistButton = this;
            var location = String(window.location.href);
            var keywordCategory = $(this).attr('keyword-category');
            var returnField = $(this).attr('return-field');
            var selectionType = $(this).attr('picklist-type');
            var formId = $(this).attr('form-id');
            var returnFieldName = $(this).attr('return-field-name');
            var returnFormName = $(this).attr('formname');
            var displayColumnsFields = $(this).attr('display_columns');
            var selection_Value_Type = $(this).attr('selection-type');
            var displayColumns = '';

            if (displayColumnsFields != '' && displayColumnsFields) {
                displayColumns = displayColumnsFields.split(',');
            }


            if (location.indexOf('formbuilder') > -1) {
                mode = "KeywordDialog";
                var picklistMode = {
                    Mode: mode
                }
            } else {
                mode = "KeywordPicklist";
                var picklistMode = {
                    Mode: mode,
                    Code: keywordCategory
                }
            }


            if (selectionType == 'Forms' && mode == 'KeywordPicklist') {
                self.getRequests(formId, '', function(result) {

                    var exemptions = ['0', '1', '2', 'request_id', 'first_name', 'last_name', 'middle_name',
                        'form_status', 'requestor_id', 'processors_id', 'processor_lastname'];

                    var ret = '<h3><i class="icon-key"></i> Please select ' + returnFormName + '</h3>';
                    ret += '<div class="hr"></div>';
                    ret += '<div></div>';
                    ret += '<div><input type="text" class="input-medium request_search" placeholder="Search" row-return-field="' + returnField + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" formId = "' + formId + '" field-name="' + returnFieldName + '" display-columns="' + displayColumns + '"></div>';
                    ret += '<div style="overflow:auto;width:100%;height:500px" class="request_view">';
                    ret += '<table  class="table_data display_data dataTable requestTable">';
                    ret += '<tr>';

                    for (var key in result[0]) {
                        if (exemptions.indexOf(key) == -1 && displayColumns.indexOf(key) >= 0) {
                            ret += '<th>' + key + '</th>';
                        }
                    }
                    ret += '</tr>';

                    var keyIndex = 0;
                    for (var index in result) {
                        keyIndex = 0;
                        ret += '<tr style="cursor:pointer" row-return-field="' + returnField + '" data="' + result[index][returnFieldName] + '" mode="' + picklistMode.Mode + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" class="keyword-category">';
                        for (var key in result[index]) {
                            if (exemptions.indexOf(key) == -1 && displayColumns.indexOf(key) >= 0) {
                                if (keyIndex == 0 && selection_Value_Type == 'Multiple') {
                                    ret += '<td><label><input type="checkbox" name="chk_selected_values" value="' + result[index][returnFieldName] + '">' + result[index][key] + '</label></td>';
                                } else {
                                    ret += '<td>' + result[index][key] + '</td>';
                                }
                                keyIndex++;
                            }


                        }
                        ret += '</tr>';
                    }

//                    for (var index in result) {
//                        ret += '<tr style="cursor:pointer" row-return-field="' + returnField + '" data="' + result[index].Code + ' - ' + result[index].Description + '" mode="' + picklistMode.Mode + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" code="' + result[index].Code + '"class="keyword-category">';
//                        ret += '<td>' + result[index].Code + '</td>';
//                        ret += '<td>' + result[index].Description + '</td>';
//                        ret += '</tr>';
                    //                    }
                    ret += '</table>';
                    ret += '</div>';
                    ret += '<div class="fields"><div class="label_basic"></div>';

                    if (selection_Value_Type == 'Multiple') {
                        // <input type="button" class="btn-blueBtn select_form_picklist" return-field="' + returnField + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" id="select_form_picklist" value="Ok">
                        ret += '<div class="input_position" style="margin-top:5px;text-align:right;"><input type="button" class="btn-blueBtn select_form_picklist_multiple" return-field="' + returnField + '" dialog-button-id="" id="select_form_picklist_multiple" value="Ok"><input type="button" style="margin-left:5px;" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div>';
                    } else {
                        ret += '<div class="input_position" style="margin-top:5px;text-align:right;"><input type="button" style="margin-left:5px;" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div>';
                    }
                    ret += '</div>';

                    ui.unblock();
                    jDialog(ret, "", "900", "", "", function() {
                    });

                });
            } else {
                self.showKeywordDialog(picklistMode, function(data) {
                    result = JSON.parse(data);

                    var ret = '<h3><i class="icon-key"></i> Picklist</h3>';
                    ret += '<div class="hr"></div>';
                    ret += '<div></div>';
                    ret += '<div class="fields selection"><div class="label_basic"> Selection:</div><div class="input_position"><input type="radio" name="workspace_title" checked="checked" data-type="picklist_selection" style="margin-top:5px;margin-right:5px" value="Forms" />Forms<input type="radio" name="workspace_title" data-type="picklist_selection" style="margin-top:5px;margin-right:5px" value="Keywords" />Keywords</div></div>';
                    ret += '<div class="display keyword_search"><input type="text" class="input-medium search-keyword" placeholder="Search" row-return-field="' + returnField + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" keyword-category = "' + keywordCategory + '"></div>';
                    ret += '<div style="overflow:auto;height:200px" class="display keyword_view">';
                    ret += '<table  class="table_data display_data dataTable keywordTable">';
                    ret += '<tr><th>Code</th> <th>Description</th></tr>';

                    for (var index in result) {
                        ret += '<tr style="cursor:pointer" row-return-field="' + returnField + '" data="' + result[index].Code + ' - ' + result[index].Description + '" mode="' + picklistMode.Mode + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" code="' + result[index].Code + '"class="keyword-category">';
                        if (mode == 'KeywordPicklist' && selection_Value_Type == 'Multiple') {
                            ret += '<td><label><input type="checkbox" name="chk_selected_values" value="' + result[index].Code + ' - ' + result[index].Description + '">' + result[index].Code + '</input></label></td>';
                        } else {
                            ret += '<td>' + result[index].Code + '</td>';
                        }
                        ret += '<td>' + result[index].Description + '</td>';
                        ret += '</tr>';

                    }
                    ret += '</table>';
                    ret += '</div>';
                    ret += '<div class="fields form_selection">';
                    ret += '<div class="label_basic">Form:</div>';
                    ret += '<div class="input_position"><select class="form-select picklist_form_type" name="picklist_form_type" id="picklist_form_type" style="margin-top:5px;"><option value="0">----------------------------Select----------------------------</option><select></div>';
                    ret += '</div>';
                    ret += '<div class="fields form_selection">';
                    ret += '<div class="label_basic">Return Field:</div>';
                    ret += '<div class="input_position"><select class="form-select picklist_form_field" name="picklist_form_field" id="picklist_form_field" style="margin-top:5px;"><option value="0">----------------------------Select----------------------------</option><select></div>';
                    ret += '</div>';
                    ret += '<div class="fields form_selection">';
                    ret += '<div class="label_basic">Display Columns:</div>';
                    ret += '<div class="input_position display_columns" style="overflow:auto;padding:5px;border:1px Solid #ccc;height:200px;width:98%"></div>';
                    ret += '</div>';
                    ret += '<div class="fields"><div class="label_basic"></div>';

                    if (mode == 'KeywordPicklist' && selection_Value_Type == 'Multiple') {
                        ret += '<div class="input_position" style="margin-top:5px;text-align:right;"><input type="button" class="btn-blueBtn select_form_picklist_multiple" return-field="' + returnField + '" dialog-button-id="" id="select_form_picklist_multiple" value="Ok"><input type="button" style="margin-left:5px;" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div>';
                    } else if (mode == 'KeywordPicklist' && selection_Value_Type != 'Multiple') {
                        ret += '<div class="input_position" style="margin-top:5px;text-align:right;"><input type="button" style="margin-left:5px;" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div>';
                    } else {
                        ret += '<div class="input_position" style="margin-top:5px;text-align:right;"><img src="/images/loader/load.gif" class="display saveFormLoad" style="margin-right:5px;margin-top:2px;"><input type="button" class="btn-blueBtn select_form_picklist" return-field="' + returnField + '" dialog-button-id="' + $(picklistButton).attr('picklist-button-id') + '" id="select_form_picklist" value="Ok"><input type="button" style="margin-left:5px;" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div>';
                    }

                    ret += '</div>';


                    ui.unblock();
                    jDialog(ret, "", "", "", "", function() {
                    });

                    self.getForms(function(data) {
                        $('.picklist_form_type').html('<option value="0">----------------------------Select----------------------------</option>');
                        for (var index in data) {
                            $('.picklist_form_type').append('<option value="' + data[index].wsID + '" fields="' + data[index].active_fields + '">' + data[index].form_name + '</option>');
                        }
                    });


                    if (mode == "KeywordPicklist") {
                        $('.keyword_search').removeClass('display');
                        $('.keyword_view').removeClass('display');
                        $('.selection').addClass('display');
                        $('.form_selection').addClass('display');
                    }
                });
            }
        });

        $('body').on('dblclick', '.keyword-category', function() {
            var picklistID = $(this).attr('dialog-button-id');
            var code = $(this).attr('code');
            var mode = $(this).attr('mode');
            var returnField = $(this).attr('row-return-field');
            var data = $(this).attr('data');
            if (mode === 'KeywordDialog') {
                $('[picklist-button-id="' + picklistID + '"]').attr('picklist-type', 'Keywords');
                $('[picklist-button-id="' + picklistID + '"]').attr('keyword-category', code);
                $('#' + returnField).attr('placeholder', data);
            } else {
                $('#' + returnField).attr('code', code);
                $('#' + returnField).val(data);
                $('#' + returnField).change();
            }

            $('#popup_cancel').click();
        });

        $('body').on('keyup', '.request_search', function(event) {
            if (event.keyCode == 13) {
                var returnField = $(this).attr('row-return-field');
                var buttonId = $(this).attr('dialog-button-id');
                var returnFieldName = $(this).attr('field-name');
                var searchValue = $(this).val();
                var formId = $(this).attr('formId');
                var displayColumnsFields = $(this).attr('display-columns');
                var displayColumns = '';
                if (displayColumnsFields != '' && displayColumnsFields) {
                    displayColumns = displayColumnsFields.split(',');
                }


                self.getRequests(formId, searchValue, function(result) {
                    var exemptions = ['0', '1', '2', 'request_id', 'first_name', 'last_name', 'middle_name',
                        'form_status', 'requestor_id', 'processors_id', 'processor_lastname'];

                    var ret = '<tr>';

                    for (var key in result[0]) {
                        if (exemptions.indexOf(key) == -1 && displayColumns.indexOf(key) >= 0) {
                            ret += '<th>' + key + '</th>';
                        }
                    }
                    ret += '</tr>';
                    for (var index in result) {
                        ret += '<tr style="cursor:pointer" row-return-field="' + returnField + '" data="' + result[index][returnFieldName] + '"  dialog-button-id="' + buttonId + '" class="keyword-category">';
                        for (var key in result[index]) {
                            if (exemptions.indexOf(key) == -1 && displayColumns.indexOf(key) >= 0) {
                                ret += '<td>' + result[index][key] + '</td>';
                            }
                        }
                        ret += '</tr>';
                    }

                    $('.requestTable').html(ret);
                });
            }
        });

        $('body').on('keyup', '.search-keyword', function(event) {
            if (event.keyCode == 13) {
                var search = $(this).val();
                var location = String(window.location.href);
                var returnField = $(this).attr('row-return-field');
                var buttonId = $(this).attr('dialog-button-id');
                var keywordCategory = $(this).attr('keyword-category');

                if (location.indexOf('formbuilder') > -1) {
                    mode = "KeywordDialog";
                    var picklistMode = {
                        Mode: mode,
                        Search: search
                    }
                } else {
                    mode = "KeywordPicklist";
                    var picklistMode = {
                        Mode: mode,
                        Code: keywordCategory,
                        Search: search
                    }
                }
                self.showKeywordDialog(picklistMode, function(data) {
                    result = JSON.parse(data);

                    var ret = '';
                    ret += '<tr><th>Code</th> <th>Description</th></tr>';

                    for (var index in result) {
                        ret += '<tr style="cursor:pointer" row-return-field="' + returnField + ' " data="' + result[index].Code + ' - ' + result[index].Description + '" mode="' + picklistMode.Mode + '" dialog-button-id="' + buttonId + '" code="' + result[index].Code + '"class="keyword-category">';
                        ret += '<td>' + result[index].Code + '</td>';
                        ret += '<td>' + result[index].Description + '</td>';
                        ret += '</tr>';
                    }
                    ret += '</table>';

                    $('.keywordTable').html(ret);
                });
            }
        });
    },
    showKeywordDialog: function(picklistMode, callback) {
        $.get('/ajax/keywords_dialog',
                picklistMode
                , function(data) {
                    callback(data);
                });
    },
    getForms: function(callback) {
        $.post('/ajax/search', {
            action: 'getForm'
        }, function(data) {
            data = JSON.parse(data);
            callback(data);
        });
    }
    , getRequests: function(formId, search_value, callback) {
        $.post('/ajax/search', {
            action: 'getRequest',
            id: formId,
            search_value: search_value,
            field: '0',
            start: 0
        }, function(data) {
            data = JSON.parse(data);
            callback(data);
        });
    }
}